反射机制--获取Class中的字段

来源:互联网 发布:mac里的照片导入ipad 编辑:程序博客网 时间:2024/05/16 16:17

前面我们获取到了Class中的构造函数,现在我们来获取Class中的字段

package text;import java.lang.reflect.Field;public class ReflectDemo3 {public static void main(String[] args) throws Exception {getFieldDemo();}/* * 获取字节码文件中的字段 * */public static void getFieldDemo() throws Exception{Class clazz=Class.forName("text.Person");//Field field=clazz.getField("age");    //只能获取公有的字段,在这里不能获取到私有字段ageField field=clazz.getDeclaredField("age");  //只能获取本类中的所有字段,包含私有System.out.println(field);  //输出:private int text.Person.age//对私有字段的访问取消权限检查:暴力访问(不建议使用)field.setAccessible(true);Object obj=clazz.newInstance();  //创建一个对象field.set(obj, 89);  //设置int类型数据值为89Object o=field.get(obj);System.out.println(o);}}
运行结果:



0 0
原创粉丝点击