如何通过反射修改列表

发布于 2024-12-18 23:16:48 字数 477 浏览 2 评论 0原文

我已经设法通过反射访问类变量,并将其存储在字段变量中。我也有该字段所属的类。我想使用反射将 Field 对象添加到此列表中,如何将 Field 对象转换为列表。

我通过反射访问的列表变量(并存储在 Field 对象中)我希望能够添加到它。

谢谢

import java.util.ArrayList;


    public class Test 
    {
        private ArrayList<Integer> aList = new ArrayList<Integer>();

        //some methods...
    }

    Field field = myObject.getClass().getField("aList");;
    field.setAccessible(true);
    //some how add an integer to that list

I have managed to access a class variable via reflection, and have it stored in a Field variable. I also have the class that field belongs too. How do i transform the Field object in to a List as I want to add to this List using reflection.

The List variable i am accessing via reflection ( and am storing in a Field object) I want to be able to add to it.

Thanks

import java.util.ArrayList;


    public class Test 
    {
        private ArrayList<Integer> aList = new ArrayList<Integer>();

        //some methods...
    }

    Field field = myObject.getClass().getField("aList");;
    field.setAccessible(true);
    //some how add an integer to that list

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗藏城府 2024-12-25 23:16:48

未经测试:

ArrayList<Integer> myList = (ArrayList<Integer>) field.get(myObject);
myList.add(5);

我假设以上就是您想要做的事情?从您的代码示例来看有点不清楚。

另外,由于该字段是私有的,您将需要使用 getDeclaredField() 而不是 getField() (如您在示例中使用的那样)。

Untested:

ArrayList<Integer> myList = (ArrayList<Integer>) field.get(myObject);
myList.add(5);

I am assuming that the above is what you are trying to do? It is a little bit unclear from your code example.

Also, since the field is private you will need to use getDeclaredField() instead of getField() (as you use in your example).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文