java 泛型方法 return 类型

java generic method return type

在下面的代码中,方法"bla()" returns ArrayList of Object 而不是String,怎么来的?

public class MyClass<T>{   
        public ArrayList<String> bla(){
            return new ArrayList<String>();
        }

        public static void foo(){
           new MyClass().bla().add([here auto complete says "Object" not "String"])
        }
    }

因为你还没有参数化这个新的实例创建表达式

new MyClass()

结果值是原始类型 MyClassJava Language Specification states

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.

也就是

public ArrayList<String> bla(){
    return new ArrayList<String>();
}

现在被视为

public ArrayList bla() {
    return new ArrayList<String>();
}

return 类型本身就是原始类型 ArrayList 并且其 add 方法的类型也成为其擦除的原始类型,即。 Object 来自通用变量 T.

显然,您仍然可以将 String 添加到需要 Object 的方法中,但是对于具有 MyClass 实例的正确参数化视图的任何人来说,类型安全性都会被破坏.

阅读:

  • What is a raw type and why shouldn't we use it?