呵呵,你这样写就是可以打印出3啊,你是在同一个类中访问private类型的变量x当然是可以的,private访问权限就是在同一个类中才可见。写在两个类中就不可见了。代码如下:
package heima.reflect.test;
import java.lang.reflect.Field;
class ReflectPoint {
private int x;
int y;
public ReflectPoint(int x, int y) {
this.x = x;
this.y = y;
}
}
public class ReflectPointTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt1 = new ReflectPoint(3, 5);
Field fieldX = pt1.getClass().getDeclaredField("x");
// Field fieldX=pt1.getClass().getField("x");
[color=Red]// fieldX.setAccessible(true);[/color]
System.out.println(fieldX.get(pt1));
}
}
执行时报错:
Exception in thread "main" java.lang.IllegalAccessException: Class heima.reflect.test.ReflectPointTest can not access a member of class heima.reflect.test.ReflectPoint with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.Field.doSecurityCheck(Unknown Source)
at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at heima.reflect.test.ReflectPointTest.main(ReflectPointTest.java:21)
加上红色那句就能打印出3了。并不是什么1.7的新特性,估计你用的也不是1.7的jdk. |