如何实例化 ArrayList<?> 并通过 Java 反射添加项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1093443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:36:34  来源:igfitidea点击:

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

javareflectionarraylist

提问by user82334

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.

我正在编写一个将 xml 转换为 Java 对象的反序列化方法。我想动态地执行此操作并避免编写对特定类型的硬编码引用。

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.

如果这是一个微不足道的问题,请原谅我,因为我是一名学习 Java 的 C# 开发人员。

Thanks!

谢谢!

采纳答案by Gareth Davis

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.

希望这可以帮助。

回答by Mike Chaliy

In java generics are just syntax sugar and they do not exist in runtime. This is why you cannot programmatically create generic objects in runtime. Try to create non generic list and cast (however I am not sure as my experience is limited with GWT).

在 Java 中泛型只是语法糖,它们在运行时不存在。这就是您不能在运行时以编程方式创建通用对象的原因。尝试创建非通用列表并进行转换(但是我不确定,因为我的 GWT 经验有限)。

回答by oxbow_lakes

You'll have to create a raw typedList(i.e. with no type parameters).

您必须创建一个原始类型List(即没有类型参数)。

List subs = deserialize( ... );

If you were to set the raw typed Liston your class directly:

如果您要List直接在类上设置原始类型:

obj.setSubObjects(subs); //You'll get an "unchecked cast" warning at compile time

Although the compiler will emit a warning, it is legal Java code and will run just fine at runtime because the parameter-type information is lost (i.e. at runtime, there is no difference between a Listand a List<SomeClass>). You can of course set it reflectively also.

尽管编译器会发出警告,但它是合法的 Java 代码,并且在运行时可以正常运行,因为参数类型信息丢失了(即在运行时, aList和 a之间没有区别List<SomeClass>)。你当然也可以反射性地设置它。

回答by Brian Kent

It seems like the real issue here is going from XML to java objects. If that is the case (and since you are new to Java), a better solution than rolling your own may be to investigate existing technologies such as:

似乎这里真正的问题是从 XML 到 Java 对象。如果是这种情况(并且由于您是 Java 新手),比自己动手更好的解决方案可能是调查现有技术,例如: