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)