获取新实例的泛型参数

时间:2015-10-21 14:11:25

标签: java generics

我需要创建泛型类的实例。不知道该用什么作为参数。

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?
    }
}

1 个答案:

答案 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);
}