Why is it allowed to access Java private fields vi

2019-01-17 06:05发布

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?

7条回答
成全新的幸福
2楼-- · 2019-01-17 06:35

From: http://java.sun.com/docs/books/tutorial/reflect/

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

It's a tool that lets one break some rules, one can throw it over his foot or use it properly.

查看更多
登录 后发表回答