3

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

TobiP
  • 43
  • 7
  • 2
    By not using `<>` parameters (as would have been `new Test<>(String.class);`), the generic typing is disabled. – Joop Eggen Jun 12 '19 at 09:27

1 Answers1

0

As Joop Eggen mentioned in his comment, the Problem was using a raw type by omitting the diamond operator <> when instantiating the Test class

//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

Raw Types Documentation

TobiP
  • 43
  • 7