天天看点

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

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

操作对象类:

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

}