反射认识_02_反射成员变量Field
包01:
package ReflectionConstructor; public class ReflectionFieldPoint { private int x; public int y; public ReflectionFieldPoint(int x, int y) { super(); this.x = x; this.y = y; } }
包02:
package ReflectionConstructor;
import java.lang.reflect.Field; /** * 反射, * 获得成员变量 */ public class ReflectionField { public static void main(String[] args) throws Exception { ReflectionFieldPoint point1=new ReflectionFieldPoint(3, 8); /**y是public*/ Field fieldY=point1.getClass().getField("y"); //fieldY值是5吗? 不是!fieldY是ReflectionFieldPoint类的y //point1对应的y是5 int y=(int)fieldY.get(point1);//得到对象的x值 System.out.println(y); /** x是private*/ Field fieldX=point1.getClass().getDeclaredField("x");
fieldX.setAccessible(true);//因为x是private,要设置成可以访问 int x=(int)fieldX.get(point1);//得到对象的x值 System.out.println(x); } }