设计一个方法,该方法,能修改任意对象中,指定成员变量的值
核心:field对象.set(obj,newValue)
1 package reflection;
2
3 import java.lang.reflect.Field;
4 import java.util.Arrays;
5
6 public class Practice1 {
7 public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException {
8 TargetClass targetClass = new TargetClass();
9 setAll(targetClass,"testA",999);
10 System.out.println(targetClass.toString());
11
12
13
14 }
15 public static void setAll(Object targetPbj,String fieldName, Object newValue) throws NoSuchFieldException, IllegalAccessException {
16 //第一步,获取目标对象所属类型的,字节码文件对象 通过对象.getClass()
17 Class aClass = targetPbj.getClass();
18
19 //第二步,在获取到的Class对象中,指定名称的成员变量(Field对象)
20 Field modifyField = aClass.getDeclaredField(fieldName);
21
22 //不知道权限,setAccessible(true),提前解决权限问题
23 modifyField.setAccessible(true);
24
25 //第三步,在指定对象上修改,指定成员变量的值 void set(Object obj,Object newValue)
26 modifyField.set(targetPbj,newValue);
27
28
29 }
30 }
1 package reflection;
2
3 public class TargetClass {
4 private int testA=666;
5 //private boolean testOk=false;
6 public void test(){
7
8 }
9 @Override
10 public String toString(){
11 return "TargetClass{"+
12 "private int testA="+testA+
13 "}";
14 }
15 }