如何使用反射实例化具有泛型类的java.util.ArrayList [英] How To Instantiate a java.util.ArrayList with Generic Class Using Reflection
问题描述
如何使用反射实例化具有泛型类的java.util.ArrayList?我正在编写一个在目标对象上设置java.util.List的方法。目标对象和通用类型的列表在运行时知道:
How To Instantiate a java.util.ArrayList with Generic Class Using Reflection? I am writing a method that sets java.util.List on target object. A target object and a generic type of list is knowing in runtime:
public static void initializeList(Object targetObject, PropertyDescriptor prop, String gtype) {
try {
Class clazz = Class.forName("java.util.ArrayList<"+gtype+">");
Object newInstance = clazz.newInstance();
prop.getWriteMethod().invoke(targetObject, newInstance);
} catch (Exception e) {
e.printStackTrace();
}
}
推荐答案
object在执行时不知道它的泛型类型。只需创建一个原始类型的新实例( java.util.ArrayList
)。目标对象不会知道差异(因为不是任何区别)。
An object doesn't know about its generic type at execution time. Just create a new instance of the raw type (java.util.ArrayList
). The target object won't know the difference (because there isn't any difference).
基本上Java泛型是一个编译时的技巧,在编译的类中使用元数据,但只是在执行时进行转换。有关详细信息,请参阅 Java泛型常见问题解答。
Basically Java generics is a compile-time trick, with metadata in the compiled classes but just casting at execution time. See the Java generics FAQ for more information.
这篇关于如何使用反射实例化具有泛型类的java.util.ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!