How to instantiate an ArrayList<?> and add an item through reflection with Java?

arraylist, java, reflection

Solution

Should be something pretty close to:

Object list = field.getType().newInstance();

Method add = List.class.getDeclaredMethod("add",Object.class);

add.invoke(list, addToAddToList);

Hope this helps.

Problem

I am writing a deserialization method that converts xml to a Java object. I would like to do this dynamically and avoid writing hard coded references to specific types. For example this is a simplified version of one of my classes. ``` public class MyObject { public ArrayList<SubObject> SubObjects = new ArrayList<SubObject>(); } ``` Here is a stripped down version of the method: ``` public class Serializer { public static <T> T fromXml(String xml, Class<T> c) { T obj = c.newInstance(); Field field = obj.getClass().getField("SubObjects"); //help : create instance of ArrayList<SubObject> and add an item //help#2 : field.set(obj, newArrayList); return obj; } } ``` Calling this method would look like this: ``` MyObject obj = Serializer.fromXml("myxmldata", MyObject.class); ``` Forgive me if this is a trivial problem as I am a C# developer learning Java. Thanks!

Original source