java代码中,常常将一个类的成员变量置为private
在类的外面获取此类的私有成员变量的value时,需要注意:
测试类:
- public class AccessibleTest {
- private int id;
- private String name;
- public AccessibleTest() {
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
Main类:
- public class Main {
- public static void main(String[] args) throws Exception {
- Class clazz = Class.forName("com.test.accessible.AccessibleTest");
- AccessibleTest at = new AccessibleTest();
- at.setId(1);
- at.setName("AT");
- for (Field f : clazz.getDeclaredFields()) {
- f.setAccessible(true);//AccessibleTest类中的成员变量为private,故必须进行此操作
- System.out.println(f.get(at));//获取当前对象中当前Field的value
- }
- }
- }
如果没有在获取Field之前调用setAccessible(true)方法,异常:
- java.lang.IllegalAccessException:
- Class com.test.accessible.Main
- can not access
- a member of class com.test.accessible.AccessibleTest
- with modifiers "private"
当然在AccessibleTest类的内部(AccessibleTest的内部类除外)
进行如上操作则不需要调用setAccesible()方法