java 反射 实例化 泛型,如何使用反射实例化具有泛型类的java.util.ArrayList
![Image 1][]
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”);
Object newInstance = clazz.newInstance();
prop.getWriteMethod().invoke(targetObject, newInstance);
} catch (Exception e) {
e.printStackTrace();
}
}
解决方案
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).
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.
[Image 1]:
还没有评论,来说两句吧...