使用反射将对象添加到arraylist

时间:2018-04-13 21:06:52

标签: java reflection

我有这个设置

public class ClassA {   
    //I cannot modify or access this class
    private List<Object> list = new ArrayList<>();  
}

public class ClassB {

    public void entry(String... args) {
        ClassA instance = ClassRegistry.find(ClassA.class); 
        //add using reflection
        //instance.list.add(new Object());
    }
}

如何使用反射将对象添加到该列表?

我试过

Field list = instance.getClass().getDeclaredField("list");
list.setAccessible(true);
ArrayList<Object> actualList = (ArrayList<Object>) list.get(instance);
actualList.add(new Object());
list.set(instance, actualList);

但它没有用。列表仍然是空的。

3 个答案:

答案 0 :(得分:0)

您的代码应该有效。看一下代码示例

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

public class ReflectionApp {

    private static ClassA classA = new ClassA();

    public static void main(String[] args) throws NoSuchFieldException, IllegalArgumentException,
            IllegalArgumentException, IllegalAccessException {
        ClassB classB = new ClassB();
        classB.entry("Foo", "Bar");
    }

    public static class ClassA {
        //I cannot modify or access this class

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

        @Override
        public String toString() {
            return "ClassA{" + "list=" + list + '}';
        }

    }

    public static class ClassB {

        public void entry(String... args) throws NoSuchFieldException, IllegalArgumentException,
                IllegalAccessException {
            ClassA instance = classA;
            // Do the reflection
            Field list = instance.getClass().getDeclaredField("list");
            list.setAccessible(true);
            ArrayList<Object> actualList = (ArrayList<Object>) list.get(instance);
            for( Object arg : args ){
                actualList.add(arg);
            }
            list.set(instance, actualList);
            System.out.println(actualList);
            System.out.println(classA);
        }
    }
}

答案 1 :(得分:0)

事实证明,实际情况确实不同,多亏了无论谁指出这一点。

答案 2 :(得分:-2)

您可以尝试以下代码

ClassA instance = new ClassA();
Field list = ClassA.class.getDeclaredField("list");
list.setAccessible(true);
ArrayList<Object> actualList = (ArrayList<Object>) list.get(instance);
actualList.add(new Object());
list.set(instance, actualList);