加載字節(jié)碼文件洛波,獲取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);
//第一個參數(shù): 要操作的是哪一個對象里面的成員變量
//第二個參數(shù): 需要設(shè)置的值
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());