我希望能够让我的构造函数(其中一个)决定它想要使用的列表的实现。我想出的代码在没有警告的情况下编译得很好,但是 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);
}
}