所以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)
因此类型擦除是为了向后兼容,但为什么保留超类型类型参数呢?元数据是否已更新以支持它?
为什么一个而不是另一个?
它是为编译时类型安全而完成的.如果超级阶级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).