[code]public class ReflectPoint{
private int x;
public int y;
......
ReflectPoint pt1 = new RelectPoint(3,5);
Field fieldY = pt1.getClass().getField("y");
//fieldY的值不是5,因为fieldY不是对象身上的变量,而是类上,必须要用它去取某个对象上对应的值
System.out.println(fieldY.get(pt1));
Field fieldX = pt1.getClass().getDeclaredField("x");
fieldX.setAccessible(true);
System.out.println(fieldX.get(pt1));
//张老师的比喻,看到钱,但是拿不到,就去抢!fieldX.setAccessible(true);这句赋予你抢的权利!
}[/code] |