Can java private data members be accessed from outside the class?

Aarun picture Aarun · Dec 26, 2012 · Viewed 54.8k times · Source

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.

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Dec 26, 2012

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;
    }