我希望能够(我的一个)构造函数决定它想要使用的列表实现。我提出的代码编译得很好而没有警告,但IDE(eclipse)在注释行上抱怨,为什么以及如何推断类型?
public class GenericClassTest<T> {
private List<T> list;
//stuff...
public GenericClassTest(Class<? extends List> listCreator)
throws InstantiationException, IllegalAccessException {
this.list = listCreator.newInstance(); // how to infer type T? where
// does diamondoperator go?
}
public static void main(String[] args) throws InstantiationException,
IllegalAccessException {
GenericClassTest<Integer> one = new GenericClassTest<>(ArrayList.class);
GenericClassTest<String> two = new GenericClassTest<>(LinkedList.class);
one.list.add(13);
two.list.add("Hello");
System.out.println(one.list);
System.out.println(two.list);
}
}
答案 0 :(得分:4)
你真的不需要。请记住,type-erasure
无论如何都会在运行时用T
替换Object
。因此,在运行时,您将始终拥有List<Object>
。因此,T
是构造调用的一部分并不重要,因为它无论如何都会被忽略。泛型是编译时的便利,它们在运行时不会做很多事情。
答案 1 :(得分:0)
如果您想在代码中使用泛型,请尝试以下操作:
class Sample {
static <T,L extends List<T>> L newList(Class<L> clazz)
throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
static <T> void mainCode() throws InstantiationException, IllegalAccessException {
List<T> list;
list = Sample.<String, ArrayList<String>>newList(ArrayList.class);
}