加载字节码文件,获取Class类对象
Class cls = Class.forName("com.qfedu.a_reflect.Person");
获取所有用public修饰的成员变量
Field[] allPublicFields = cls.getFields();
for (Field field : allPublicFields) {
System.out.println(field);
}
获取所有的成员变量
Field[] allFields = cls.getDeclaredFields();
for (Field field : allFields) {
System.out.println(field);
}
Field aPublicField = cls.getField("test");
System.out.println(aPublicField);
set方法
//set(Oject obj, Object value);
//第一个参数: 要操作的是哪一个对象里面的成员变量
//第二个参数: 需要设置的值
Person p = (Person) cls.getConstructor(int.class, String.class).
newInstance(1, "狗蛋");
aPublicField.set(p, 20);
System.out.println("44" + p.test);
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
Field aStaticField = cls.getField("testStatic");
System.out.println(aStaticField);
aStaticField.set(null, 20);
System.out.println(Person.testStatic);
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
Field aPrivateField = cls.getDeclaredField("id");
System.out.println(aPrivateField);
aPrivateField.setAccessible(true);
aPrivateField.set(p, 10);
System.out.println(p.getId());
网友评论