如何通过反射修改列表
我已经设法通过反射访问类变量,并将其存储在字段变量中。我也有该字段所属的类。我想使用反射将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
未经测试:
我假设以上就是您想要做的事情?从您的代码示例来看有点不清楚。
另外,由于该字段是私有的,您将需要使用 getDeclaredField() 而不是 getField() (如您在示例中使用的那样)。
Untested:
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).