Break OO privacy: Difference between revisions

Added D example
(Added Wren)
(Added D example)
Line 364:
*** - READ from #<INPUT BUFFERED FILE-STREAM CHARACTER #P"funky.lisp" @44>:
#<PACKAGE FUNKY> has no external symbol with name "WOBBLINESS"</pre>
 
=={{header|D}}==
 
Private members can be accessed by other code in the same module. You can access private members of structs/classes imported from another module using compile time reflection.
 
breakingprivacy.d:
<lang D>module breakingprivacy;
 
struct Foo
{
int[] arr;
private:
int x;
string str;
float f;
}</lang>
 
app.d:
<lang D>import std.stdio;
import breakingprivacy;
 
void main()
{
auto foo = Foo([1,2,3], 42, "Hello World!", 3.14);
writeln(foo);
// __traits(getMember, obj, name) allows you to access any field of obj given its name
// Reading a private field
writeln("foo.x = ", __traits(getMember, foo, "x"));
// Writing to a private field
__traits(getMember, foo, "str") = "Not so private anymore!";
writeln("Modified foo: ", foo);
}</lang>
 
{{out}}
<lang text>Foo([1, 2, 3], 42, "Hello World!", 3.14)
foo.x = 42
Modified foo: Foo([1, 2, 3], 42, "Not so private anymore!", 3.14)</lang>
 
=={{header|E}}==
Anonymous user