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

后端 未结 7 1928
暗喜
暗喜 2020-12-08 04:14

Consider this example :

import java.lang.reflect.Field;

public class Test {

    public static void main(String[] args) {
        C c = new C();
        try         


        
7条回答
  •  星月不相逢
    2020-12-08 04:37

    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.

提交回复
热议问题