如何将泛型类传递给Java中的方法?

Ant*_*ton 9 java generics methods arguments dynamic

假设我们有一个函数创建给定特定类的对象:

public static <T> T createObject(Class<T> generic) {
    try {
        return generic.newInstance();
    } catch (Exception ex) {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

我们可以轻松地使用该函数来创建非泛型类型的实例.

public static void main(String[] args) {
    Foo x = createObject(Foo.class);
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用泛型类型执行相同的操作?

public static void main(String[] args) {
    ArrayList<Foo> x = createObject(ArrayList<Foo>.class); // compiler error
}
Run Code Online (Sandbox Code Playgroud)

Eti*_*tel 8

Java中的泛型是通过类型擦除实现的.

这意味着ArrayList<T>,在运行时,是一个ArrayList.编译器只是为您插入强制转换.

您可以使用以下方法测试:

ArrayList<Integer> first = new ArrayList<Integer>();
ArrayList<Float> second = new ArrayList<Float>();

if(first.getClass() == second.getClass())
{
    // should step in the if
}
Run Code Online (Sandbox Code Playgroud)