public static void getFileDemo() throws ClassNotFoundException, SecurityException, NoSuchFieldException, InstantiationException, IllegalAccessException {
/*
* 获取字节码中的字段
*/
Class clazz=Class.forName("cn.soft.p.bean.People");
Field field=null;//clazz.getField("age");//只获取本类,但包含私有。
field=clazz.getDeclaredField("age");//只获取本类,但包含私有
System.out.println(field);
Object obj=clazz.newInstance();
Object o=field.get(obj);
System.out.println(o);
}
}
这段代码运行结果如
public int cn.soft.p.bean.People.age
Exception in thread "main" java.lang.IllegalAccessException: Class cn.soft.test.RelexFiletest can not access a member of class cn.soft.p.bean.People with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
at java.lang.Class.newInstance0(Class.java:349)
at java.lang.Class.newInstance(Class.java:308)
at cn.soft.test.RelexFiletest.getFileDemo(RelexFiletest.java:32)
at cn.soft.test.RelexFiletest.main(RelexFiletest.java:17)