在Java中,为什么对参数化类型的构造函数进行无类型调用会引发编译器警告?为什么用静态方法做类似的事情是可以的?例如:
class Test<T> {
Test() {}
static <T> Test<T> create() {
return new Test<T>();
}
@SuppressWarnings("unused")
public static void main(String[] args) {
Test<String> warning = new Test(); // compiler warning - why?
Test<String> okay = Test.create(); // no warning here - why?
Test<String> okay2 = Test.<String>create(); // why doesn't it need this?
}
}
Run Code Online (Sandbox Code Playgroud)
因为您将无类型实例分配给类型变量.你的三个案例:
new Test<String>()这是正确的.new Test<T>()(而不仅仅是new Test())来制作泛型类型的explict .