public class A {
public int a1 = 1;
private int a2 = 2;
public start String s;
}
获取成员 包括私有属性 :
public class Main {
public static void main(String[] args) throws Exception {
Class class_ = Class.forName("fanshe_chaozhuo.A");
Object o = class_.getDeclaredConstructor().newInstance();
// 获取某属性
Field field = class_.getDeclaredField("a1");
// 获取值
System.out.println(field.get(o));
Field field1 = class_.getDeclaredField("a2");
// a2为provate 开始暴力破解
field1.setAccessible(true);
System.out.println(field1.get(o));
// 并且可以修改值
field1.set(o,9999);
System.out.println(field1.get(o));
}
}
运行结果
细节:
修改静态属性时,对象名是可以省略的
class .....
public start String s;
......
Field field2 = class_.getDeclaredField("s");
field2.set(null,"sdas");
System.out.println(o);