如何实例化一个ArrayList<>并通过与Java反射增加一个项目? [英] How to instantiate an ArrayList<?> and add an item through reflection with Java?

查看:387
本文介绍了如何实例化一个ArrayList<>并通过与Java反射增加一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写XML转换为Java对象的反序列化方法。我想动态地做到这一点,避免编写硬codeD引用特定类型。

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

原谅我,如果这是一个很小的问题,因为我是一个C#开发人员学习Java。

Forgive me if this is a trivial problem as I am a C# developer learning Java.

谢谢!

推荐答案

应该是pretty接近:

Should be something pretty close to:

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

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

add.invoke(list, addToAddToList);

希望这有助于。

这篇关于如何实例化一个ArrayList&LT;&GT;并通过与Java反射增加一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆