Java通过反射设置私有变量

  1. public class PrivateTest {        
  2.     private String name = "hello";        
  3.        
  4.     public String getName() {        
  5.         return name;        
  6.     }        
  7. }   
[java] view plaincopy
 
  1. import java.lang.reflect.Field;  
  2.   
  3. public class ReflectionTest {        
  4.     public static void main(String[] args) throws Exception {        
  5.         PrivateTest pt = new PrivateTest();   
  6.                 
  7.         Class<PrivateTest> clazz = PrivateTest.class;        
  8.                 
  9.         Field field = clazz.getDeclaredField("name");        
  10.         field.setAccessible(true);        
  11.         field.set(pt, "world");        
  12.         field.setAccessible(false);        
  13.                 
  14.         System.out.println(pt.getName());        
  15.     }        
  16. }  

参考:http://www.iteye.com/problems/38606

原文地址:https://www.cnblogs.com/veins/p/3954098.html