在Java中可以通过反射进行获取实体类中的字段值,当未设置Field的setAccessible方法为true时,会在调用的时候进行访问安全检查,会抛出IllegalAccessException异常。
@org.junit.Test
public void test2() throws IllegalAccessException {
People people = new People();
Class<? extends People> aClass = people.getClass();
people.setName("sherlock");
people.setAge(18);
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field : declaredFields) {
// field.setAccessible(true);
System.out.println(field.get(people));
}
}

使用 setAccessible() 可以临时改变访问权限,就可以获取私有成员变量的值。
@org.junit.Test
public void test2() throws IllegalAccessException {
People people = new People();
Class<? extends People> aClass = people.getClass();
people.setName("sherlock");
people.setAge(18);
Field[] declaredFields = aClass.getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
System.out.println(field.get(people));
}
}

网友评论