Why is it allowed to access Java private fields via reflection?

Consider this example :

import java.lang.reflect.Field;

public class Test {

    public static void main(String[] args) {
        C c = new C();
        try {
            Field f = C.class.getDeclaredField("a");
            f.setAccessible(true);
            Integer i = (Integer)f.get(c);
            System.out.println(i);
        } catch (Exception e) {}
    }
}

class C {
    private Integer a =6;
}

It seems illogical that you are allowed to access private fields of classes with reflection. Why is such a functionality available? Isn't it "dangerous" to allow such access?


Solution 1:

Private is intended to prevent accidental misuse, not as a security mechanism. If you choose to bypass it then you can do so at your own risk and the assumption you know what you are doing.

Solution 2:

Both getDeclaredField() and setAccessible() are actually checked by the security manager and will throw an exception when your code is not allowed to do this. More often than not you won't notice it, because Java code is often run without a security manager.

One important exception are Applets, which always run with a security manager.

Solution 3:

Yes it's not nice but it does allow frameworks such as Java Serialization to work.

Setting the accessible flag in a reflected object permits sophisticated applications with sufficient privilege, such as Java Object Serialization or other persistence mechanisms, to manipulate objects in a manner that would normally be prohibited.

I beleive that the functionality can be disabled through the SecurityManager

http://javabeans.asia/2008/10/12/how_to_set_securitymanager_and_java_security_policy_programmatically.html

Solution 4:

Reflection is dangerous. Period.

What's the point in limiting the utility of a really dangerous system for the sake of ever so slightly increased safety?

Also, automated serialization requires the ability to "suck the brains" out of any class; ignoring access modifiers is a necessity in this case.