Break OO privacy: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: added to Phix/Class)
m (→‎{{header|Java}}: correct mixed use of tabs and spaces)
Line 655: Line 655:
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.)
<lang java>import java.lang.reflect.*;
<lang java>import java.lang.reflect.*;

class Example {
class Example {
private String _name;
private String _name;
public Example(String name) { _name = name; }
public Example(String name) { _name = name; }
public String toString() { return "Hello, I am " + _name; }
public String toString() { return "Hello, I am " + _name; }
}
}

public class BreakPrivacy {
public class BreakPrivacy {
public static final void main(String[] args) throws Exception {
public static final void main(String[] args) throws Exception {
Example foo = new Example("Eric");
Example foo = new Example("Eric");

for (Field f : Example.class.getDeclaredFields()) {
for (Field f : Example.class.getDeclaredFields()) {
if (f.getName().equals("_name")) {
if (f.getName().equals("_name")) {
// make it accessible
// make it accessible
f.setAccessible(true);
f.setAccessible(true);

// get private field
// get private field
System.out.println(f.get(foo));
System.out.println(f.get(foo));

// set private field
// set private field
f.set(foo, "Edith");
f.set(foo, "Edith");
System.out.println(foo);
System.out.println(foo);

break;
break;
}
}
}
}
}
}
}</lang>
}</lang>
{{out}}
{{out}}