Rahul
Rahul

Reputation: 922

How to populate an objects List<String> member variable with String values using Java Reflection

A sample of what I need to do.

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

How do I populate an objects List with String values through reflection? Thanks

Upvotes: 1

Views: 1174

Answers (2)

bezmax
bezmax

Reputation: 26122

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

Upvotes: 4

AlexR
AlexR

Reputation: 115328

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");

Upvotes: 4

Related Questions