转载: 通过反射操作类的私有属性

原文地址:

http://blog.csdn.net/qustmeng/article/details/54691933

 

对于类的私有属性,如果没有提供公用方法去修改它,我们可以通过反射方法实现。下面为简单例子

import java.util.ArrayList;
import java.util.List;

public class A {

	private List<Integer> list = new ArrayList<Integer>();

	public List<Integer> getList() {
		return list;
	}
	
}

 

 import java.lang.reflect.Field;
import java.util.List;

public class Test {
    
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        A a = new A();
        try {
            Field field = A.class.getDeclaredField("list");
            field.setAccessible(true);
            List<Integer> myList = (List<Integer>) field.get(a);
            

            myList.add(1);
            myList.add(2);

            myList.add(3);

            myList.add(4);

            myList.add(5);


            for (Integer i : a.getList()) {
                System.out.println(i);
            }
            
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}

 

 

 

 

效果图:

 

 

 

posted on 2017-06-03 14:37  Angry_Panda  阅读(305)  评论(0编辑  收藏  举报

导航