首页 > 其他 > 详细

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

时间:2017-06-03 15:40:49      阅读:322      评论:0      收藏:0      [点我收藏+]

原文地址:

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();
        }
    }

}

 

 

 

 

效果图:

技术分享

 

技术分享

 

技术分享

 

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

原文:http://www.cnblogs.com/devilmaycry812839668/p/6937289.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!