如何使用Java Reflection </string>使用String值填充对象List <string>成员变量

时间:2011-12-20 09:27:44

标签: java reflection arraylist

我需要做的一个样本。

Field field=myBean.getClass().getDeclaredField("listOfStringMemberVar");
field.setAccessible(true);
field.set(myBean, value);
//value is a String. I want to add it to the listOfStringMemberVar

如何通过反射使用String值填充对象List? 感谢

2 个答案:

答案 0 :(得分:4)

field.set(myBean, Collections.singletonList("myvalue")); // for one element list

// if list already exists and you just want to append your value
List<String> theList = (List<String>)field.get(myBean);
list.add("myvalue");

答案 1 :(得分:4)

List<String> list = (List<String>)Field.get(myBean);
list.add(value);