level 4
lqscjnd
楼主
public class ReflectDemo{
public static void main(String[] args) throws Exception{
//通过Class方法获得类文件
Class clazz = Class.forName("day28.Persons");//该行没有问题,Class方法的确得到了Person.Class的对象
//通过方法获得私有字段
Field fi = null;
fi = clazz.getDeclaredField("age");//获得名为age的字段(属性);
//获得类的对象,以方便调用字段
Object obj = clazz.newInstance();
//取消权限检查
fi.setAccessible(true);
//获得对象obj中的age;
Object o = fi.get(obj);
fi.set(obj, 24);
System.out.println(fi.getInt(obj));
System.out.println(o);
}
输出结果为
24
0
为什么直接输出o值为0,醉了·····
2017年12月29日 11点12分
1
public static void main(String[] args) throws Exception{
//通过Class方法获得类文件
Class clazz = Class.forName("day28.Persons");//该行没有问题,Class方法的确得到了Person.Class的对象
//通过方法获得私有字段
Field fi = null;
fi = clazz.getDeclaredField("age");//获得名为age的字段(属性);
//获得类的对象,以方便调用字段
Object obj = clazz.newInstance();
//取消权限检查
fi.setAccessible(true);
//获得对象obj中的age;
Object o = fi.get(obj);
fi.set(obj, 24);
System.out.println(fi.getInt(obj));
System.out.println(o);
}
输出结果为
24
0
为什么直接输出o值为0,醉了·····