考虑以下例子:
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;
}
使用反射可以访问类的私有字段似乎是不合逻辑的。为什么会提供这样的功能?允许这种访问难道不是"危险"的吗?