如何使用反射实例化具有通用类的java.util.ArrayList?我正在编写一个方法,在目标对象上设置java.util.List。目标对象和列表的通用类型在运行时已知:如何使用反射实例化具有通用类的java.util.ArrayList
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();
}
}
只是为了不创建重复的答案,使用反射就像做`new ArrayList