由于引入了泛型,Class 被参数化,因此 List.class 产生 Class<List>。这很清楚。
我无法弄清楚的是如何获得一个自身参数化的类的实例,即 Class<List<String>>。就像在这个片段中一样:
public class GenTest {
static <T> T instantiate(Class<T> clazz) throws Exception {
return clazz.newInstance();
}
public static void main(String[] args) throws Exception {
// Is there a way to avoid waring on the line below
// without using @SuppressWarnings("unchecked")?
// ArrayList.class is Class<ArrayList>, but I would like to
// pass in Class<ArrayList<String>>
ArrayList<String> l = GenTest.instantiate(ArrayList.class);
}
}
我经常遇到这个问题的变体,但我仍然不知道是我错过了什么,还是真的没有更好的方法。感谢您的建议。