- public static void main(String[] args) throws Exception {
-
- //通过calss获取类路径,获取空构造函数
- Constructor<?> clazz=Class.forName("itcast.javabean.Person").getConstructor();
-
- Person person=(Person) clazz.newInstance();//实例化对象
- //Person person = (Person) Class.forName("itcast.javabean.Person").newInstance();
-
- Field fieldName = person.getClass().getDeclaredField("name");//获取bean里的对象名
- fieldName.setAccessible(true);//因为我的对象名定义的是私有的只能强制取出来,就是暴力反射
- fieldName.set(person, "lizhen");
- Field fieldAge = person.getClass().getDeclaredField("age");
- fieldAge.setAccessible(true);
- fieldAge.set(person, 22);
- System.out.println(fieldName.get(person));
- System.out.println(fieldAge.get(person));
- changeValue(person);
- System.out.println(person.getName() + person.getAge());
- }
复制代码 |