码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-06-03 16:19:13      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:port   exce   etl   private   效果图   print   declare   .com   images   

原文地址:

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

}

 

 

 

 

效果图:

技术分享

 

技术分享

 

技术分享

 

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

标签:port   exce   etl   private   效果图   print   declare   .com   images   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!