本帖最后由 罗全涛 于 2012-1-2 15:54 编辑
java反射机制访问pravte私有成员,请教,有代码
主函数中:
ReflectPoint pt1 = new ReflectPoint(3,5);
Field fieldY = pt1.getClass().getDeclaredField("y");
fieldY.setAccessible(true);
System.out.println(fieldY.get(pt1));
47 Field fieldX = pt1.getClass().getDeclaredField("X");
48 fieldX.setAccessible(true);
49 System.out.println(fieldX.get(pt1));
ReflectPoint类的定义
public class ReflectPoint {
private int x;
private int y;
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
报错:
5
Exception in thread "main" java.lang.NoSuchFieldException: X
at java.lang.Class.getDeclaredField(Class.java:1882)
at cn.itcast.day1.ReflectTest.main(ReflectTest.java:47)
思考:同样是通过class实例的getDeclaredField()方法取得了私有成员,
并且两次都设置成了可访问,问什么y输出了结果,而x却报错了。 |