Possible Duplicate:
Is it possible in Java to access private fields via reflection
Is there any way so that we can call the private data members of a class in java, can be accessed outside the class. I want this for a tricky question banks. As much my java experience i think this is possible, but i don't know how to do it.
1) You can do it with reflection, if SecurityManager allows
class B {
private int x = 2;
}
public class A {
public static void main(String[] args) throws Exception {
Field f = B.class.getDeclaredField("x");
f.setAccessible(true);
f.get(new B());
}
}
2) in case of inner classes
class A {
private int a = 1;
class B {
private int b = 2;
private void xxx() {
int i = new A().a;
};
}
private void aaa() {
int i = new B().b;
}