给定一个泛型类Test<T>
和采取一个构造Class
泛型参数的public Test(Class<T> clazz){}
为什么没有编译器能够正确推断的构造函数实例化该泛型类型new Test(String.class)
当调用构造函数new Test(String.class)
,编译器似乎不能推断类型Test<String>
什么是这个原因?使用静态工厂方法,编译器推断正确的类型:
Test.java
class Test<T> {
public Test(Class<T> clazz) {}
public static <C> Test<C> create(Class<C> clazz) {
return new Test<>(clazz);
}
}
Test<Integer> y = new Test(String.class); // works fine at both compile time and runtime, runtime error occurs when calling another method that relies on the generic type parameter
//Test<Integer> x = Test.create(String.class); // does not compile
作为乔普埃根在他的评论中提到的,问题是使用原始类型省略了钻石操作<>
实例化测试类时
//Test<Integer> y = new Test<>(String.class); // doesn't compile
//Test<Integer> y = new Test<String>(String.class); // doesn't compile
Test<String> y = new Test<>(String.class); // compiles with correct types
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句