Given a generic class Test<T>
and a constructor that takes the Class
of the generic parameter public Test(Class<T> clazz){}
Why doesn't the compiler correctly infer that generic type on constructor instantiation new Test(String.class)
When calling the constructor new Test(String.class)
the compiler seems to not infer the type Test<String>
What's the reason for this? Using a static factory method, the compiler infers the correct type:
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