在Java中,为什么无类型调用参数化类型的构造函数会引发编译器警告?

0 java generics

在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)

Kon*_*lph 8

因为您将无类型实例分配给类型变量.你的三个案例:

  1. 因为new Test<String>()这是正确的.
  2. 因为Java支持基于返回类型的自动类型推断,即它可以暗示这里的missign泛型参数,并且方法内部,你通过使用new Test<T>()(而不仅仅是new Test())来制作泛型类型的explict .
  3. 因为2. ;-)