Java - 创建扩展List的对象

Lim*_*eth 4 java generics constructor casting list

如何创建具有指定类型参数的列表?例如:

LinkedList<Integer> list = createList(LinkedList.class, Integer.class);
Run Code Online (Sandbox Code Playgroud)

我已经尝试为它创建一个方法,但该方法在创建新实例时不包含type参数.

public static <T, L extends List<T>> L createList(Class<L> listClazz, Class<T> valueClazz) throws Exception
{
    return listClazz.getConstructor().newInstance();

    //Instead of
    //  new L<T>();
    //does
    //  new L();
}
Run Code Online (Sandbox Code Playgroud)

我希望我的问题很清楚,谢谢你的帮助.

Roh*_*ain 8

你不能这样做.泛型在运行时没有业务,因此您无法使用反射在运行时创建参数化实例.在运行时,LinkedList<Intege>只是一个LinkedList.类型信息 - Integer在编译时通过"类型擦除"擦除.关键是,你为什么要这样做?