Break OO privacy: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
{{task}} [[Category:Object oriented]]
[[Category:Object oriented]]
{{omit from|AWK}}
{{task}}
{{omit from|BASIC}}
{{omit from|BBC BASIC}}
{{omit from|C}}
{{omit from|Déjà Vu}}
{{omit from|GUISS}}
{{omit from|Haskell}}
{{omit from|Locomotive Basic}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Mathematica}}
{{omit from|R}}
{{omit from|Rust}}
{{omit from|SmileBASIC}}
{{omit from|ZX Spectrum Basic}}
{{omit from|6502 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|Z80 Assembly}}
{{omit from|8086 Assembly}}
{{omit from|x86 Assembly}}
{{omit from|ARM Assembly}}

Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
Line 28: Line 8:
as unidiomatic at best, and poor programming practice at worst.
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.

=={{header|ABAP}}==
=={{header|ABAP}}==


Similar to C++, ABAP allows the declaration of friends which can be both classes and interfaces. All subclasses of friend classes are automatically friends of the source class. For example if classA (source) has classB as a friend and classC is a subclass of classB then classC is a friend of classA. Similarly all implementing classes of friend interfaces are friends of the source class. Also all interfaces which contain the befriended interface as a component are friends of the source class.
Similar to C++, ABAP allows the declaration of friends which can be both classes and interfaces. All subclasses of friend classes are automatically friends of the source class. For example if classA (source) has classB as a friend and classC is a subclass of classB then classC is a friend of classA. Similarly all implementing classes of friend interfaces are friends of the source class. Also all interfaces which contain the befriended interface as a component are friends of the source class.


<syntaxhighlight lang=ABAP>class friendly_class definition deferred.
<syntaxhighlight lang="abap">class friendly_class definition deferred.


class my_class definition friends friendly_class .
class my_class definition friends friendly_class .
Line 75: Line 54:
endclass.
endclass.
</syntaxhighlight>
</syntaxhighlight>

=={{header|Ada}}==
=={{header|Ada}}==


One of the great criticisms of Pascal was "there is no escape". The reason was that sometimes you have to convert the incompatible. We start with a package, which defines the data type which holds the secret.
One of the great criticisms of Pascal was "there is no escape". The reason was that sometimes you have to convert the incompatible. We start with a package, which defines the data type which holds the secret.


<syntaxhighlight lang=Ada>package OO_Privacy is
<syntaxhighlight lang="ada">package OO_Privacy is


type Confidential_Stuff is tagged private;
type Confidential_Stuff is tagged private;
Line 97: Line 75:
One way to read the password is by using the generic function Unchecked_Conversion:
One way to read the password is by using the generic function Unchecked_Conversion:


<syntaxhighlight lang=Ada>with OO_Privacy, Ada.Unchecked_Conversion, Ada.Text_IO;
<syntaxhighlight lang="ada">with OO_Privacy, Ada.Unchecked_Conversion, Ada.Text_IO;


procedure OO_Break_Privacy is
procedure OO_Break_Privacy is
Line 122: Line 100:
Another way to bypass privacy is using a child package. Ada child packages have access to their parents' private data structures (somewhat similar to "friends" in C++"):
Another way to bypass privacy is using a child package. Ada child packages have access to their parents' private data structures (somewhat similar to "friends" in C++"):


<syntaxhighlight lang=Ada>package OO_Privacy.Friend is -- child package of OO.Privacy
<syntaxhighlight lang="ada">package OO_Privacy.Friend is -- child package of OO.Privacy
function Get_Password(Secret: Confidential_Stuff) return String;
function Get_Password(Secret: Confidential_Stuff) return String;
Line 128: Line 106:
end OO_Privacy.Friend;</syntaxhighlight>
end OO_Privacy.Friend;</syntaxhighlight>


<syntaxhighlight lang=Ada>package body OO_Privacy.Friend is -- implementation of the child package
<syntaxhighlight lang="ada">package body OO_Privacy.Friend is -- implementation of the child package
function Get_Password(Secret: Confidential_Stuff) return String is
function Get_Password(Secret: Confidential_Stuff) return String is
Line 137: Line 115:
Now here is the program that uses the child package, to read the secret:
Now here is the program that uses the child package, to read the secret:


<syntaxhighlight lang=Ada>with OO_Privacy.Friend, Ada.Text_IO;
<syntaxhighlight lang="ada">with OO_Privacy.Friend, Ada.Text_IO;
procedure Bypass_OO_Privacy is
procedure Bypass_OO_Privacy is
Line 154: Line 132:


In fact, the password has to be the default one, because we cannot change the password. For that purpose, we would have to write a setter procedure, and either include it in the package OO_Privacy, or in a child package of OO_Privacy. (Or we could use Unchecked_Conversion to overwrite the default password -- but that is bad style.)
In fact, the password has to be the default one, because we cannot change the password. For that purpose, we would have to write a setter procedure, and either include it in the package OO_Privacy, or in a child package of OO_Privacy. (Or we could use Unchecked_Conversion to overwrite the default password -- but that is bad style.)

=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Reflection;
using System.Reflection;


Line 175: Line 152:
}</syntaxhighlight>
}</syntaxhighlight>
{{out}}
{{out}}
<syntaxhighlight lang=text>42</syntaxhighlight>
<syntaxhighlight lang="text">42</syntaxhighlight>

=={{header|C++}}==
=={{header|C++}}==


C++ has the 'friend' keyword to indicate that one class should have access to the private data of another. Here's a simple use case. (Please note that this code is not thread-safe.)
C++ has the 'friend' keyword to indicate that one class should have access to the private data of another. Here's a simple use case. (Please note that this code is not thread-safe.)


<syntaxhighlight lang=cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


class CWidget; // Forward-declare that we have a class named CWidget.
class CWidget; // Forward-declare that we have a class named CWidget.
Line 249: Line 225:
}</syntaxhighlight>
}</syntaxhighlight>
{{out}}
{{out}}
<syntaxhighlight lang=text>Widget spawning. There are now 1 Widgets instanciated.
<syntaxhighlight lang="text">Widget spawning. There are now 1 Widgets instanciated.
Widget spawning. There are now 2 Widgets instanciated.
Widget spawning. There are now 2 Widgets instanciated.
Widget dieing. There are now 1 Widgets instanciated.
Widget dieing. There are now 1 Widgets instanciated.
Line 258: Line 234:
Without the "friend" mechanism, it's still possible to meaningfully modify any member in another class, as long as you know that member's address in memory, and its type. Here's the same program as above, but using a pointer to m_uicount, rather a reference to the factory:
Without the "friend" mechanism, it's still possible to meaningfully modify any member in another class, as long as you know that member's address in memory, and its type. Here's the same program as above, but using a pointer to m_uicount, rather a reference to the factory:


<syntaxhighlight lang=cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


class CWidget; // Forward-declare that we have a class named CWidget.
class CWidget; // Forward-declare that we have a class named CWidget.
Line 324: Line 300:
delete pWidget2;
delete pWidget2;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Clojure}}==
=={{header|Clojure}}==
You can use the var-quote macro to get values from private variables. Here's an example of a variable 'priv' marked private in namespace 'a':
You can use the var-quote macro to get values from private variables. Here's an example of a variable 'priv' marked private in namespace 'a':
<syntaxhighlight lang=clojure>
<syntaxhighlight lang="clojure">
(ns a)
(ns a)
(def ^:private priv :secret)
(def ^:private priv :secret)
Line 338: Line 313:


Clojure can also access Java private variables with the same strategy that Java uses. As a convenience, use the [http://clojuredocs.org/clojure_contrib/clojure.contrib.reflect/get-field get-field] function from clojure.contrib.reflect. Here's an example of grabbing the private field "serialVersionUID" from java.lang.Double:
Clojure can also access Java private variables with the same strategy that Java uses. As a convenience, use the [http://clojuredocs.org/clojure_contrib/clojure.contrib.reflect/get-field get-field] function from clojure.contrib.reflect. Here's an example of grabbing the private field "serialVersionUID" from java.lang.Double:
<syntaxhighlight lang=clojure>
<syntaxhighlight lang="clojure">
user=> (get-field Double "serialVersionUID" (Double/valueOf 1.0))
user=> (get-field Double "serialVersionUID" (Double/valueOf 1.0))
-9172774392245257468
-9172774392245257468
</syntaxhighlight>
</syntaxhighlight>

=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


Line 358: Line 332:
A symbol can be present in more than one package, such that it can be internal in some of them, and external in others.
A symbol can be present in more than one package, such that it can be internal in some of them, and external in others.


<syntaxhighlight lang=lisp>(defpackage :funky
<syntaxhighlight lang="lisp">(defpackage :funky
;; only these symbols are public
;; only these symbols are public
(:export :widget :get-wobbliness)
(:export :widget :get-wobbliness)
Line 410: Line 384:
*** - READ from #<INPUT BUFFERED FILE-STREAM CHARACTER #P"funky.lisp" @44>:
*** - READ from #<INPUT BUFFERED FILE-STREAM CHARACTER #P"funky.lisp" @44>:
#<PACKAGE FUNKY> has no external symbol with name "WOBBLINESS"</pre>
#<PACKAGE FUNKY> has no external symbol with name "WOBBLINESS"</pre>

=={{header|D}}==
=={{header|D}}==


Line 416: Line 389:


breakingprivacy.d:
breakingprivacy.d:
<syntaxhighlight lang=D>module breakingprivacy;
<syntaxhighlight lang="d">module breakingprivacy;


struct Foo
struct Foo
Line 429: Line 402:


app.d:
app.d:
<syntaxhighlight lang=D>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;
import breakingprivacy;
import breakingprivacy;


Line 447: Line 420:


{{out}}
{{out}}
<syntaxhighlight lang=text>Foo([1, 2, 3], 42, "Hello World!", 3.14)
<syntaxhighlight lang="text">Foo([1, 2, 3], 42, "Hello World!", 3.14)
foo.x = 42
foo.x = 42
Modified foo: Foo([1, 2, 3], 42, "Not so private anymore!", 3.14)</syntaxhighlight>
Modified foo: Foo([1, 2, 3], 42, "Not so private anymore!", 3.14)</syntaxhighlight>

=={{header|E}}==
=={{header|E}}==


Line 456: Line 428:


{{improve|E|Show an example of such an evaluator once it is available.}}
{{improve|E|Show an example of such an evaluator once it is available.}}

=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
{{trans|C#}}
{{trans|C#}}
<syntaxhighlight lang=fsharp>open System
<syntaxhighlight lang="fsharp">open System
open System.Reflection
open System.Reflection


Line 477: Line 448:
{{out}}
{{out}}
<pre>System.Int32 = 42</pre>
<pre>System.Int32 = 42</pre>

=={{header|Factor}}==
=={{header|Factor}}==
From the [http://docs.factorcode.org/content/article-word-search-private.html documentation for private words]: ''"Privacy is not enforced by the system; private words can be called from other vocabularies, and from the listener. However, this should be avoided where possible."''
From the [http://docs.factorcode.org/content/article-word-search-private.html documentation for private words]: ''"Privacy is not enforced by the system; private words can be called from other vocabularies, and from the listener. However, this should be avoided where possible."''
Line 483: Line 453:
This example uses the private word ''sequence/tester'' from the vocabulary ''sets.private''. It tries to count the elements in an intersection of two sets.
This example uses the private word ''sequence/tester'' from the vocabulary ''sets.private''. It tries to count the elements in an intersection of two sets.


<syntaxhighlight lang=factor>( scratchpad ) USING: sets sets.private ;
<syntaxhighlight lang="factor">( scratchpad ) USING: sets sets.private ;
( scratchpad ) { 1 2 3 } { 1 2 4 } sequence/tester count .
( scratchpad ) { 1 2 3 } { 1 2 4 } sequence/tester count .
2</syntaxhighlight>
2</syntaxhighlight>
Line 489: Line 459:
There is better way to do the same, without any private words.
There is better way to do the same, without any private words.


<syntaxhighlight lang=factor>( scratchpad ) USE: sets
<syntaxhighlight lang="factor">( scratchpad ) USE: sets
( scratchpad ) { 1 2 3 } { 1 2 4 } intersect length .
( scratchpad ) { 1 2 3 } { 1 2 4 } intersect length .
2</syntaxhighlight>
2</syntaxhighlight>

=={{header|Forth}}==
=={{header|Forth}}==
{{works with|Forth}}
{{works with|Forth}}
Line 499: Line 468:
Needs the FMS-SI (single inheritance) library code located here:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
http://soton.mpeforth.com/flag/fms/index.html
<syntaxhighlight lang=forth>include FMS-SI.f
<syntaxhighlight lang="forth">include FMS-SI.f


99 value x \ create a global variable named x
99 value x \ create a global variable named x
Line 517: Line 486:
f1 print \ 50
f1 print \ 50
</syntaxhighlight>
</syntaxhighlight>

=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
FreeBASIC generally does a good job of maintaining OO privacy as it doesn't support reflection and even its OffsetOf keyword cannot obtain the offset within a user defined type of a private or protected field. You therefore have to guess the offset of a non-public field in order to be able to access it using a raw pointer though this is not generally a difficult task.
FreeBASIC generally does a good job of maintaining OO privacy as it doesn't support reflection and even its OffsetOf keyword cannot obtain the offset within a user defined type of a private or protected field. You therefore have to guess the offset of a non-public field in order to be able to access it using a raw pointer though this is not generally a difficult task.


However, as usual, macros come to the rescue and one can easily access non-public members by the simple expedient (or, if you prefer, 'dirty hack') of redefining the Private and Protected keywords to mean Public:
However, as usual, macros come to the rescue and one can easily access non-public members by the simple expedient (or, if you prefer, 'dirty hack') of redefining the Private and Protected keywords to mean Public:
<syntaxhighlight lang=freebasic>'FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">'FB 1.05.0 Win64


#Undef Private
#Undef Private
Line 548: Line 516:
1 2 3
1 2 3
</pre>
</pre>

=={{header|Go}}==
=={{header|Go}}==
Go has a <code>reflect</code> and <code>unsafe</code> package that together can do this.
Go has a <code>reflect</code> and <code>unsafe</code> package that together can do this.
Line 555: Line 522:
A relevant Go Blog article is
A relevant Go Blog article is
[http://blog.golang.org/laws-of-reflection The Laws of Reflection].
[http://blog.golang.org/laws-of-reflection The Laws of Reflection].
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 658: Line 625:


==Icon and {{header|Unicon}}==
==Icon and {{header|Unicon}}==
{{omit from|Icon}}
Unicon implements object environments with records and supporting procedures for creation, initialization, and methods. The variables in the class environment can be accessed like any other record field. Additionally, with the ''fieldnames'' procedure you can obtain the names of the class variables.
Unicon implements object environments with records and supporting procedures for creation, initialization, and methods. The variables in the class environment can be accessed like any other record field. Additionally, with the ''fieldnames'' procedure you can obtain the names of the class variables.


Line 664: Line 630:


Note: Unicon can be translated via a command line switch into icon which allows for classes to be shared with Icon code (assuming no other incompatibilities exist).
Note: Unicon can be translated via a command line switch into icon which allows for classes to be shared with Icon code (assuming no other incompatibilities exist).
<syntaxhighlight lang=unicon>link printf
<syntaxhighlight lang="unicon">link printf


procedure main()
procedure main()
Line 689: Line 655:
var 1 of foo x = 1
var 1 of foo x = 1
foo var1=-1, var2=2, var3=3</pre>
foo var1=-1, var2=2, var3=3</pre>

=={{header|J}}==
=={{header|J}}==


Line 697: Line 662:


J does support a "[http://www.jsoftware.com/help/dictionary/dx003.htm Lock Script]" mechanism - to transform a J script so that it's unreadable. However, anyone with access to a machine running the code and ordinary developer tools or who understands the "locking" technique could unlock it.
J does support a "[http://www.jsoftware.com/help/dictionary/dx003.htm Lock Script]" mechanism - to transform a J script so that it's unreadable. However, anyone with access to a machine running the code and ordinary developer tools or who understands the "locking" technique could unlock it.

=={{header|Java}}==
=={{header|Java}}==
Private fields (and in general all members) of a Java class can be accessed via reflection, but must pass a security check in order to do so. There are two such security checks, one for discovering the field at all, and another for granting access to it in order to be able to read and write it. (This in turn means that trusted applications can do this — it is in fact a mechanism used by important frameworks like Spring — but untrusted applets cannot.)
Private fields (and in general all members) of a Java class can be accessed via reflection, but must pass a security check in order to do so. There are two such security checks, one for discovering the field at all, and another for granting access to it in order to be able to read and write it. (This in turn means that trusted applications can do this — it is in fact a mechanism used by important frameworks like Spring — but untrusted applets cannot.)
<syntaxhighlight lang=java>import java.lang.reflect.*;
<syntaxhighlight lang="java">import java.lang.reflect.*;
class Example {
class Example {
Line 737: Line 701:


(Note: somewhere between Java 8 and Java 11 this stopped working because the <code>value</code> field of <code>String</code> is <code>final</code>. The reflective access is still possible, but changing a final field isn't.)
(Note: somewhere between Java 8 and Java 11 this stopped working because the <code>value</code> field of <code>String</code> is <code>final</code>. The reflective access is still possible, but changing a final field isn't.)
<syntaxhighlight lang=Java>import java.lang.reflect.*;
<syntaxhighlight lang="java">import java.lang.reflect.*;
public class BreakString{
public class BreakString{
public static void main(String... args) throws Exception{
public static void main(String... args) throws Exception{
Line 753: Line 717:
5
5
</pre>
</pre>

=={{header|Julia}}==
=={{header|Julia}}==


Julia's object model is one of structs which contain data and methods which are just functions using those structs, with multiple dispatch, rather than object methods, used to distinguish similarly named calls for different object types. Julia does not therefore enforce any private fields in its structures, since, except for constructors, it does not distinguish object methods from other functions. If private fields or methods are actually needed they can be kept from view by placing them inside a module which cannot be directly accessed by user code, such as in a module within a module.
Julia's object model is one of structs which contain data and methods which are just functions using those structs, with multiple dispatch, rather than object methods, used to distinguish similarly named calls for different object types. Julia does not therefore enforce any private fields in its structures, since, except for constructors, it does not distinguish object methods from other functions. If private fields or methods are actually needed they can be kept from view by placing them inside a module which cannot be directly accessed by user code, such as in a module within a module.

=={{header|Kotlin}}==
=={{header|Kotlin}}==
For tasks such as this, reflection is your friend:
For tasks such as this, reflection is your friend:
<syntaxhighlight lang=scala>import kotlin.reflect.full.declaredMemberProperties
<syntaxhighlight lang="scala">import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.isAccessible


Line 781: Line 743:
secret -> 42
secret -> 42
</pre>
</pre>

=={{header|Logtalk}}==
=={{header|Logtalk}}==
Logtalk provides a ''context switching call'' control construct that allows a call to be executed as from within an object. It's mainly used for debugging and for writing unit tests. This control construct can be disabled on a global or per object basis to prevent it of being used to break encapsulation.
Logtalk provides a ''context switching call'' control construct that allows a call to be executed as from within an object. It's mainly used for debugging and for writing unit tests. This control construct can be disabled on a global or per object basis to prevent it of being used to break encapsulation.


In the following example, a prototype is used for simplicity.
In the following example, a prototype is used for simplicity.
<syntaxhighlight lang=logtalk>:- object(foo).
<syntaxhighlight lang="logtalk">:- object(foo).


% be sure that context switching calls are allowed
% be sure that context switching calls are allowed
Line 799: Line 760:
:- end_object.</syntaxhighlight>
:- end_object.</syntaxhighlight>
After compiling and loading the above object, we can use the following query to access the private method:
After compiling and loading the above object, we can use the following query to access the private method:
<syntaxhighlight lang=logtalk>| ?- foo<<bar(X).
<syntaxhighlight lang="logtalk">| ?- foo<<bar(X).
X = 1 ;
X = 1 ;
X = 2 ;
X = 2 ;
X = 3
X = 3
true</syntaxhighlight>
true</syntaxhighlight>

=={{header|Lua}}==
=={{header|Lua}}==


Line 811: Line 771:
These can be accessed indirectly through the [https://www.lua.org/manual/5.1/manual.html#5.9 debug library].
These can be accessed indirectly through the [https://www.lua.org/manual/5.1/manual.html#5.9 debug library].


<syntaxhighlight lang=Lua>local function Counter()
<syntaxhighlight lang="lua">local function Counter()
-- These two variables are "private" to this function and can normally
-- These two variables are "private" to this function and can normally
-- only be accessed from within this scope, including by any function
-- only be accessed from within this scope, including by any function
Line 848: Line 808:


Note that there's an infinite number of other more complex ways for functions to store values in a "private" manner, and the introspection functionality of the debug library can only get you so far.
Note that there's an infinite number of other more complex ways for functions to store values in a "private" manner, and the introspection functionality of the debug library can only get you so far.

=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
We want to read two private variables, and change values without using a public method (a module or a function), and without attach a temporary method (we can do that in M2000). There is a variant in READ statemend to set references from group members (for variables and arrays, and objects) to names with a reference for each. So using these names (here in the exaample K, M) we can read and write private variables.
We want to read two private variables, and change values without using a public method (a module or a function), and without attach a temporary method (we can do that in M2000). There is a variant in READ statemend to set references from group members (for variables and arrays, and objects) to names with a reference for each. So using these names (here in the exaample K, M) we can read and write private variables.
<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Module CheckIt {
Group Alfa {
Group Alfa {
Line 873: Line 832:
CheckIt
CheckIt
</syntaxhighlight>
</syntaxhighlight>

=={{header|Nim}}==
=={{header|Nim}}==
File oo.nim:
File oo.nim:
<syntaxhighlight lang=nim>type Foo* = object
<syntaxhighlight lang="nim">type Foo* = object
a: string
a: string
b: string
b: string
Line 884: Line 842:
Foo(a: a, b: b, c: c)</syntaxhighlight>
Foo(a: a, b: b, c: c)</syntaxhighlight>
By not adding a <code>*</code> to <code>Foo</code>'s members we don't export them. When we import this module we can't use them directly:
By not adding a <code>*</code> to <code>Foo</code>'s members we don't export them. When we import this module we can't use them directly:
<syntaxhighlight lang=nim>var x = createFoo("this a", "this b", 12)
<syntaxhighlight lang="nim">var x = createFoo("this a", "this b", 12)


echo x.a # compile time error</syntaxhighlight>
echo x.a # compile time error</syntaxhighlight>
The easiest way to get a debug view of any data:
The easiest way to get a debug view of any data:
<syntaxhighlight lang=nim>echo repr(x)</syntaxhighlight>
<syntaxhighlight lang="nim">echo repr(x)</syntaxhighlight>
Output:
Output:
<pre>[a = 0x7f6bb87a7050"this a",
<pre>[a = 0x7f6bb87a7050"this a",
Line 894: Line 852:
c = 12]</pre>
c = 12]</pre>
More fine-grained:
More fine-grained:
<syntaxhighlight lang=nim>import typeinfo
<syntaxhighlight lang="nim">import typeinfo


for key, val in fields(toAny(x)):
for key, val in fields(toAny(x)):
Line 912: Line 870:
Key c
Key c
is an integer with value: 12</pre>
is an integer with value: 12</pre>

=={{header|Objective-C}}==
=={{header|Objective-C}}==
In older versions of the compiler, you can simply access a private field from outside of the class. The compiler will give a warning, but you can ignore it and it will still compile. However, in current compiler versions it is now a hard compile error.
In older versions of the compiler, you can simply access a private field from outside of the class. The compiler will give a warning, but you can ignore it and it will still compile. However, in current compiler versions it is now a hard compile error.
Line 919: Line 876:
One solution is to use Key-Value Coding. It treats properties and instance variables as "keys" that you can get and set using key-value coding methods.
One solution is to use Key-Value Coding. It treats properties and instance variables as "keys" that you can get and set using key-value coding methods.


<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


@interface Example : NSObject {
@interface Example : NSObject {
Line 964: Line 921:
Another solution is to use a category to add methods to the class (you can have categories in your code modify any class, even classes compiled by someone else, including system classes). Since the new method is in the class, it can use the class's private instance variables with no problem.
Another solution is to use a category to add methods to the class (you can have categories in your code modify any class, even classes compiled by someone else, including system classes). Since the new method is in the class, it can use the class's private instance variables with no problem.


<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


@interface Example : NSObject {
@interface Example : NSObject {
Line 1,023: Line 980:
Finally, you can access the instance variable directly using runtime functions.
Finally, you can access the instance variable directly using runtime functions.


<syntaxhighlight lang=objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <objc/runtime.h>


Line 1,066: Line 1,023:
Hello, I am Edith
Hello, I am Edith
</pre>
</pre>

=={{header|OCaml}}==
=={{header|OCaml}}==


Line 1,077: Line 1,033:
The reader is advised to stop reading here.
The reader is advised to stop reading here.


<syntaxhighlight lang=ocaml>class point x y =
<syntaxhighlight lang="ocaml">class point x y =
object
object
val mutable x = x
val mutable x = x
Line 1,117: Line 1,073:
Broken coord: (-1, -1)
Broken coord: (-1, -1)
(0, 0)</pre>
(0, 0)</pre>

=={{header|Oforth}}==
=={{header|Oforth}}==


Line 1,123: Line 1,078:


There is no other way to access attributes values from outside but to call methods on the object.
There is no other way to access attributes values from outside but to call methods on the object.

=={{header|Perl}}==
=={{header|Perl}}==
Perl's object model does not enforce privacy. An object is just a blessed reference, and a blessed reference can be dereferenced just like an ordinary reference.
Perl's object model does not enforce privacy. An object is just a blessed reference, and a blessed reference can be dereferenced just like an ordinary reference.
<syntaxhighlight lang=perl>package Foo;
<syntaxhighlight lang="perl">package Foo;
sub new {
sub new {
my $class = shift;
my $class = shift;
Line 1,144: Line 1,098:
<pre>I am ostensibly private
<pre>I am ostensibly private
I am ostensibly private</pre>
I am ostensibly private</pre>

=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/Class}}
{{libheader|Phix/Class}}
Line 1,150: Line 1,103:
We can easily break that privacy mechanism via low-level routines with the required simulated/fake context,<br>
We can easily break that privacy mechanism via low-level routines with the required simulated/fake context,<br>
and at the same time be reasonably confident that no-one is ever going to manage to achieve that by accident.
and at the same time be reasonably confident that no-one is ever going to manage to achieve that by accident.
<!--<syntaxhighlight lang=Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no class under p2js)</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no class under p2js)</span>
<span style="color: #008080;">class</span> <span style="color: #000000;">test</span>
<span style="color: #008080;">class</span> <span style="color: #000000;">test</span>
Line 1,175: Line 1,128:
"this breaks privacy"
"this breaks privacy"
</pre>
</pre>

=={{header|PHP}}==
=={{header|PHP}}==
While normally accessing private variables causes fatal errors, it's possible to catch output of some debugging functions and use it. Known functions which can get private variables include: <code>var_dump()</code>, <code>print_r()</code>, <code>var_export()</code> and <code>serialize()</code>. The easiest to use is <code>var_export()</code> because it's both valid PHP code and doesn't recognize private and public variables.
While normally accessing private variables causes fatal errors, it's possible to catch output of some debugging functions and use it. Known functions which can get private variables include: <code>var_dump()</code>, <code>print_r()</code>, <code>var_export()</code> and <code>serialize()</code>. The easiest to use is <code>var_export()</code> because it's both valid PHP code and doesn't recognize private and public variables.


{{works with|PHP|5.1}}
{{works with|PHP|5.1}}
<syntaxhighlight lang=php><?php
<syntaxhighlight lang="php"><?php
class SimpleClass {
class SimpleClass {
private $answer = "hello\"world\nforever :)";
private $answer = "hello\"world\nforever :)";
Line 1,204: Line 1,156:
{{works with|PHP|4.x}}
{{works with|PHP|4.x}}
{{works with|PHP|5.x}}
{{works with|PHP|5.x}}
<syntaxhighlight lang=php><?php
<syntaxhighlight lang="php"><?php
class SimpleClass {
class SimpleClass {
private $answer = 42;
private $answer = 42;
Line 1,215: Line 1,167:
{{works with|PHP|5.3}}
{{works with|PHP|5.3}}
Since php 5.3, one can easily read and write any protected and private member in a object via reflection.
Since php 5.3, one can easily read and write any protected and private member in a object via reflection.
<syntaxhighlight lang=php><?php
<syntaxhighlight lang="php"><?php
class fragile {
class fragile {
private $foo = 'bar';
private $foo = 'bar';
Line 1,236: Line 1,188:
}
}
</pre>
</pre>

=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
PicoLisp uses [http://software-lab.de/doc/ref.html#transient "transient symbols"] for variables, functions, methods etc. inaccessible from other parts of the program. Lexically, a transient symbol is enclosed by double quotes.
PicoLisp uses [http://software-lab.de/doc/ref.html#transient "transient symbols"] for variables, functions, methods etc. inaccessible from other parts of the program. Lexically, a transient symbol is enclosed by double quotes.
The only way to access a transient symbol outside its namespace is to search for its name in other (public) structures. This is done by the '[http://software-lab.de/doc/refL.html#loc loc]' function.
The only way to access a transient symbol outside its namespace is to search for its name in other (public) structures. This is done by the '[http://software-lab.de/doc/refL.html#loc loc]' function.
<syntaxhighlight lang=PicoLisp>(class +Example)
<syntaxhighlight lang="picolisp">(class +Example)
# "_name"
# "_name"


Line 1,253: Line 1,204:
(setq Foo (new '(+Example) "Eric"))</syntaxhighlight>
(setq Foo (new '(+Example) "Eric"))</syntaxhighlight>
Test:
Test:
<syntaxhighlight lang=PicoLisp>: (string> Foo) # Access via method call
<syntaxhighlight lang="picolisp">: (string> Foo) # Access via method call
-> "Hello, I am Eric"
-> "Hello, I am Eric"


Line 1,273: Line 1,224:
: (get Foo (loc "_name" +Example))
: (get Foo (loc "_name" +Example))
-> "Edith"</syntaxhighlight>
-> "Edith"</syntaxhighlight>

=={{header|Python}}==
=={{header|Python}}==
Python isn't heavily into private class names. Although private class names can be defined by using a double underscore at the start of the name, such names are accessible as they are mangled into the original name preceded by the name of its class as shown in this example:
Python isn't heavily into private class names. Although private class names can be defined by using a double underscore at the start of the name, such names are accessible as they are mangled into the original name preceded by the name of its class as shown in this example:
<syntaxhighlight lang=python>>>> class MyClassName:
<syntaxhighlight lang="python">>>> class MyClassName:
__private = 123
__private = 123
non_private = __private * 2
non_private = __private * 2
Line 1,292: Line 1,242:
123
123
>>> </syntaxhighlight>
>>> </syntaxhighlight>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}
We may call into the MOP (Meta-Object Protocol) via the <tt>.^</tt> operator, and the MOP knows all about the object, including any supposedly private bits. We ask for its attributes, find the correct one, and get its value.
We may call into the MOP (Meta-Object Protocol) via the <tt>.^</tt> operator, and the MOP knows all about the object, including any supposedly private bits. We ask for its attributes, find the correct one, and get its value.
<syntaxhighlight lang=raku line>class Foo {
<syntaxhighlight lang="raku" line>class Foo {
has $!shyguy = 42;
has $!shyguy = 42;
}
}
Line 1,305: Line 1,254:
{{out}}
{{out}}
<pre>42</pre>
<pre>42</pre>

=={{header|Ruby}}==
=={{header|Ruby}}==
Ruby lets you redefine great parts of the object model at runtime and provides several methods to do so conveniently. For a list of all available methods look up the documentation of <code>Object</code> and <code>Module</code> or call informative methods at runtime (<code>puts Object.methods</code>).
Ruby lets you redefine great parts of the object model at runtime and provides several methods to do so conveniently. For a list of all available methods look up the documentation of <code>Object</code> and <code>Module</code> or call informative methods at runtime (<code>puts Object.methods</code>).
<syntaxhighlight lang=ruby>
<syntaxhighlight lang="ruby">
class Example
class Example
def initialize
def initialize
Line 1,327: Line 1,275:
p example.instance_variable_get :@private_data # => 42
p example.instance_variable_get :@private_data # => 42
</syntaxhighlight>
</syntaxhighlight>

=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}<syntaxhighlight lang=scala>class Example(private var name: String) {
{{libheader|Scala}}<syntaxhighlight lang="scala">class Example(private var name: String) {
override def toString = s"Hello, I am $name"
override def toString = s"Hello, I am $name"
}
}
Line 1,342: Line 1,289:
println(foo)
println(foo)
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Sidef}}==
=={{header|Sidef}}==
Sidef's object model does not enforce privacy, but it allows storing private attributes inside the container of an object, which is an hash:
Sidef's object model does not enforce privacy, but it allows storing private attributes inside the container of an object, which is an hash:
<syntaxhighlight lang=ruby>class Example {
<syntaxhighlight lang="ruby">class Example {
has public = "foo"
has public = "foo"
method init {
method init {
Line 1,360: Line 1,306:
# Access private attributes
# Access private attributes
say obj{:private}; #=> "secret"</syntaxhighlight>
say obj{:private}; #=> "secret"</syntaxhighlight>

=={{header|Swift}}==
=={{header|Swift}}==
Swift reflection provides a Collection of label-value pairs for struct properties
Swift reflection provides a Collection of label-value pairs for struct properties
<syntaxhighlight lang=Swift>struct Example {
<syntaxhighlight lang="swift">struct Example {
var notSoSecret = "Hello!"
var notSoSecret = "Hello!"
private var secret = 42
private var secret = 42
Line 1,377: Line 1,322:
{{out}}
{{out}}
<pre>Value of the secret is 42</pre>
<pre>Value of the secret is 42</pre>

=={{header|Tcl}}==
=={{header|Tcl}}==
Tcl's object properties are just variables in the a per-instance namespace; all that's required to get hold of them is to discover the name of the namespace concerned:
Tcl's object properties are just variables in the a per-instance namespace; all that's required to get hold of them is to discover the name of the namespace concerned:
<syntaxhighlight lang=tcl>package require Tcl 8.6
<syntaxhighlight lang="tcl">package require Tcl 8.6


oo::class create Example {
oo::class create Example {
Line 1,393: Line 1,337:
Hello, I am Eric
Hello, I am Eric
Hello, I am Edith
Hello, I am Edith

=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
Line 1,400: Line 1,343:
Like the other .NET languages, VB can use Reflection ([https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection Microsoft docs]).
Like the other .NET languages, VB can use Reflection ([https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection Microsoft docs]).


<syntaxhighlight lang=vbnet>Imports System.Reflection
<syntaxhighlight lang="vbnet">Imports System.Reflection


' MyClass is a VB keyword.
' MyClass is a VB keyword.
Line 1,418: Line 1,361:
{{out}}
{{out}}
<pre>42</pre>
<pre>42</pre>

=={{header|Wren}}==
=={{header|Wren}}==
In Wren all instance and static fields of a class are private and are prefixed by an underscore and a double underscore respectively. There is no way to break the privacy of such fields that I'm aware of (Wren doesn't have reflection). If one wants to provide public access to fields then this is done via getter and/or setter methods.
In Wren all instance and static fields of a class are private and are prefixed by an underscore and a double underscore respectively. There is no way to break the privacy of such fields that I'm aware of (Wren doesn't have reflection). If one wants to provide public access to fields then this is done via getter and/or setter methods.


However, there is no such thing as a private method. Although conventionally methods which are not intended to be called from outside the class are suffixed with an underscore, this doesn't prevent anyone from accessing them as the following example shows.
However, there is no such thing as a private method. Although conventionally methods which are not intended to be called from outside the class are suffixed with an underscore, this doesn't prevent anyone from accessing them as the following example shows.
<syntaxhighlight lang=ecmascript>class Safe {
<syntaxhighlight lang="ecmascript">class Safe {
construct new() { _safe = 42 } // the field _safe is private
construct new() { _safe = 42 } // the field _safe is private
safe { _safe } // provides public access to field
safe { _safe } // provides public access to field
Line 1,440: Line 1,382:
84
84
</pre>
</pre>

=={{header|zkl}}==
=={{header|zkl}}==
In zkl, privacy is more convention than enforced (unlike const or protected).
In zkl, privacy is more convention than enforced (unlike const or protected).
<syntaxhighlight lang=zkl>class C{var [private] v; fcn [private] f{123} class [private] D {}}
<syntaxhighlight lang="zkl">class C{var [private] v; fcn [private] f{123} class [private] D {}}
C.v; C.f; C.D; // all generate NotFoundError exceptions
C.v; C.f; C.D; // all generate NotFoundError exceptions
However:
However:
Line 1,451: Line 1,392:
C.vars //-->L(L("",Void)) (name,value) pairs</syntaxhighlight>
C.vars //-->L(L("",Void)) (name,value) pairs</syntaxhighlight>
In the case of private vars, the name isn't saved.
In the case of private vars, the name isn't saved.
{{omit from|6502 Assembly}}

{{omit from|8086 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|ARM Assembly}}
{{omit from|AWK}}
{{omit from|BASIC}}
{{omit from|BBC BASIC}}
{{omit from|C}}
{{omit from|Déjà Vu}}
{{omit from|GUISS}}
{{omit from|Haskell}}
{{omit from|Icon}}
{{omit from|Locomotive Basic}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Mathematica}}
{{omit from|Rust}}
{{omit from|R}}
{{omit from|SmileBASIC}}
{{omit from|Standard ML|not OO}}
{{omit from|Standard ML|not OO}}
{{omit from|x86 Assembly}}
{{omit from|Z80 Assembly}}
{{omit from|ZX Spectrum Basic}}