java 反射 实例化 泛型,如何使用反射实例化具有泛型类的java.util.ArrayList

客官°小女子只卖身不卖艺 2022-10-04 12:52 267阅读 0赞

![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]:

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java实例总结

    前言: 当我们在做项目的时候 ,搭建框架的时候,会经常用到泛型类来封装一些通用类或工具类。在封装泛型类的过程中,为了提升开发效率及代码简洁,会经常运用泛型内部进行实例化,用以减