-3

I want to reflect a private list in Java, add some elements to an instance of it, and set the original list to the instance. How can I do this? I tried the using fields, but Java is unable to cast a Field to a List.

ashjack
  • 65
  • 6
  • You have a field of type `List`? you want to retrieve the referenced `List` object and add something to it? – Sotirios Delimanolis Apr 07 '15 at 18:50
  • 2
    Seems like an XY problem. Why do you want to do that? If the list is private maybe there's a reason... – Alexis C. Apr 07 '15 at 18:52
  • The list contains textures for a game (Minecraft). The Minecraft Forge developers told me that to add textures from an external source I should reflect this list and add to it. – ashjack Apr 07 '15 at 18:53
  • I expect the devs to be smarter than that. Isn't there a method to add a new texture in this list? Using reflection for this seems like an ugly hack... – Alexis C. Apr 07 '15 at 18:54

1 Answers1

0

Use Field.get and Field.set.

Field field = Foo.class.getField("fieldName");
List<Bar> list = (List<Bar>) field.get(myFoo);
List<Bar> changedList = changeList(list);
field.set(myFoo, changedList);
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • I'm probably going to look like an idiot for asking this, but what should myFoo be? I tried instancing a list as an arraylist, but it gives me java.lang.IllegalArgumentException – ashjack Apr 08 '15 at 08:07