由于引入了泛型,因此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);
}
}
Run Code Online (Sandbox Code Playgroud)
我经常遇到这个问题的变化,我仍然不知道,如果我只是错过了什么,或者是否真的没有更好的方法.谢谢你的建议.