Break OO privacy: Difference between revisions

m
→‎{{header|Java}}: correct mixed use of tabs and spaces
m (→‎{{header|Phix}}: added to Phix/Class)
m (→‎{{header|Java}}: correct mixed use of tabs and spaces)
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.)
<lang java>import java.lang.reflect.*;
 
class Example {
private String _name;
public Example(String name) { _name = name; }
public String toString() { return "Hello, I am " + _name; }
}
 
public class BreakPrivacy {
public static final void main(String[] args) throws Exception {
Example foo = new Example("Eric");
 
for (Field f : Example.class.getDeclaredFields()) {
if (f.getName().equals("_name")) {
// make it accessible
f.setAccessible(true);
 
// get private field
System.out.println(f.get(foo));
 
// set private field
f.set(foo, "Edith");
System.out.println(foo);
 
break;
}
}
}
}
}
}
}</lang>
{{out}}