Field.setAccessible()方法
http://blog.csdn.net/kjfcpua/article/details/8496911
java代码中,常常将一个类的成员变量置为private
在类的外面获取此类的私有成员变量的value时,需要注意:
测试类:
1 public class AccessibleTest { 2 3 private int id; 4 private String name; 5 6 public AccessibleTest() { 7 8 } 9 10 public int getId() { 11 return id; 12 } 13 14 public void setId(int id) { 15 this.id = id; 16 } 17 18 public String getName() { 19 return name; 20 } 21 22 public void setName(String name) { 23 this.name = name; 24 } 25 26 }
Main类:
1 public class Main { 2 3 public static void main(String[] args) throws Exception { 4 Class clazz = Class.forName("com.test.accessible.AccessibleTest"); 5 AccessibleTest at = new AccessibleTest(); 6 at.setId(1); 7 at.setName("AT"); 8 for (Field f : clazz.getDeclaredFields()) { 9 f.setAccessible(true);//AccessibleTest类中的成员变量为private,故必须进行此操作 10 System.out.println(f.get(at));//获取当前对象中当前Field的value 11 } 12 13 } 14 15 }
如果没有在获取Field之前调用setAccessible(true)方法,异常:
(当然在AccessibleTest类的内部(AccessibleTest的内部类除外),进行如上操作则不需要调用setAccesible()方法)
- java.lang.IllegalAccessException:
- Class com.test.accessible.Main
- can not access
- a member of class com.test.accessible.AccessibleTest
- with modifiers "private"