为什么我们可以创建通用模板的新实例而不是Java中的泛型类型?

Sho*_*kie 3 java generics

我知道这是不可能的: 由于类型擦除new T,在哪里T是泛型类型.

那么为什么可以做new A<T>T之类通用的东西呢?例如,为什么以下编译?

static class A<T>{
    T t;
    A(T t){
        this.t=t;
    }
}

static class B<T>{

    A<T> create(T t){
        return new A<T>(t);
    }
}

public static void main (String[] args) throws java.lang.Exception
{
    A<Integer> a = new B<Integer>().create(3);
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ppo 6

因为A<Integer>在编译和运行时是一个定义良好的类型.

在概念上,中间步骤,之后:

new B<Integer>()
Run Code Online (Sandbox Code Playgroud)

你的电话.create(3)相当于打电话:

static class B {
    A<Integer> create(Integer t){
        return new A<Integer>(t);
    }
}
Run Code Online (Sandbox Code Playgroud)

擦除后,A<Integer>变为A,这是一种有效的类型.

你不能这样做,new T因为T它不是一个定义良好的类型,它只是一个标记.如果你真的需要,你可以T使用类似的东西获得相应的类并实例化一个类型的对象:

public class GenericFactory {
    <T> T create(Class<T> c) throws Exception {
        return c.newInstance();
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它像:

new GenericFactory().create(Integer.class);
Run Code Online (Sandbox Code Playgroud)

是的,那很难看.