Java Reflection,为什么在运行时保留超类型类型参数

mis*_*ist 14 java generics

所以java有类型擦除,删除类型参数(在运行时没有泛型类型).有人可以解释为什么保留超类型参数吗?

class StringList extends ArrayList<String> {
    public Type getType() {

        Type[] typeArguments = ((ParameterizedType) this.getClass()
                .getGenericSuperclass()).getActualTypeArguments();
        return typeArguments[0];
    }
}
Run Code Online (Sandbox Code Playgroud)

这意味着什么:

new ArrayList<String>()// I cannot use reflection to find out the generified type String
Run Code Online (Sandbox Code Playgroud)

new StringList()//I can use reflection to see the generic type String
Run Code Online (Sandbox Code Playgroud)

因此类型擦除是为了向后兼容,但为什么保留超类型类型参数呢?元数据是否已更新以支持它?

为什么一个而不是另一个?

Sot*_*lis 7

它是为编译时类型安全而完成的.如果超级阶级StringList被删除ArrayList,就没有办法防范

StringList stringList = new StringList();
stringList.add(new Integer(123456));
Run Code Online (Sandbox Code Playgroud)

如果类型保留在.class文件中StringList,编译器可以正确拒绝上面的源代码,因为new Integer(123456)它不是String预期的类型ArrayList<String>#add(String).

  • @mist请澄清你对_a简单`ArrayList <String>`的意思.如果您指的是局部变量,那么泛型类型不能保留在字节代码中.只有编译器在编译时才需要它.在编译(成功)代码之后,不需要对泛型类型进行其他检查. (2认同)
  • @fge是的,输入令牌.我相信它们首先出现在[这里](http://gafter.blogspot.com/2006/12/super-type-tokens.html). (2认同)