将 setAccessible
设置以后就可以跳过访问权限。
public class Boy {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.hyl.learnerJVM.jvmstack.dynamic.Boy");
Boy boy = new Boy();
boy.setName("fake");
Field name = clazz.getDeclaredField("name");
name.setAccessible(true);
Object o = name.get(boy);
// 没有通过访问权限直接获取到了
System.out.println(o);
}
}