包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); }}
新聞熱點
疑難解答