我需要创建泛型类的实例。不知道该用什么作为参数。
import java.util.List;
import java.util.ArrayList;
public class Main{
public static void main(String[] args){
Class type = someMethod(); //It could return String.class, Integer.class, MyClass.class etc
//Now I need to make a instance of something using generic parameter. I use List as example here.
List<type)> list = new ArrayList<>(); //Does not work, obvioulsy since it looks weird.
//But what does work?
}
}
答案 0 :(得分:0)
您可以通过传递所需的List
元素类来使编译器确保编译类型(非运行时)的安全性:
public static <T> List<T> makeList(@SuppressWarnings("UnusedParameters") Class<T> elClass) {
return new ArrayList<>();
}
public static void main(String[] args) {
List<String> strings = makeList(String.class);
List<Integer> ints = makeList(Integer.class);
}