原始类型成员丢失的generics类型

我在使用generics时发现了一种奇怪的行为。

在这个类Foostrings成员与T没有任何关系:

 package test; import java.util.ArrayList; public class Foo { ArrayList strings; T getSome() { return null; } } 

该类主要用于:

 package test; public class Main { public static void main() { Foo intFoo = new Foo(); Integer i = intFoo.getSome(); String s1 = intFoo.strings.get(0); Foo rawFoo = new Foo(); Object o = rawFoo.getSome(); String s2 = rawFoo.strings.get(0); // Compilation error on this line } } 

编译错误是“不兼容的类型。必需:String found:Object”。

当使用原始类型的Foo时,Java似乎忘记了StringList的String类型参数。

我的java版本是1.7.0_21

简单地说,因为rawFoo是原始的,它的非静态成员也变得原始。

这在JLS§4.8中概述:

更准确地说,原始类型被定义为以下之一:

  • 通过获取generics类型声明的名称而不带伴随类型参数列表而形成的引用类型。

  • 元素类型为原始类型的数组类型。

  • 原始类型R的非静态成员类型,它不是从R的超类或超级接口inheritance的。

注意最后一颗子弹。