Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 829
user82334 Avatar asked Jul 07 '09 16:07

user82334


1 Answers

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.

like image 54
Gareth Davis Avatar answered Oct 25 '22 06:10

Gareth Davis