なぜJavaコンパイラは、コンストラクタのインスタンス化でジェネリック型のトラックを失っていますか?

TobiP:

ジェネリッククラスを考える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

TobiP:

ジョープEggenが彼のコメントで述べたように、問題は、ダイヤモンド演算子を省略することによって、生タイプを使用していた<>テストクラスをインスタンス化するとき

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

生タイプのドキュメント

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=219172&siteId=1