问题描述
我已阅读 Neal Gafter 的 博客主题,但在许多方面仍不清楚.
I've read Neal Gafter's blog on the subject and am still unclear on a number of points.
在 Java、JVM 和现有集合 API 的当前状态下,为什么不能创建保留类型信息的集合 API 实现?难道这些不能以保留向后兼容性的方式替换 Java 未来版本中的现有实现吗?
Why is it not possible to create implementations of the Collections API that preserve type information given the current state of Java, the JVM and existing collections API? Couldn't these replace the existing implementations in a future version of Java in a way where backwards compatibility is preserved?
举个例子:
List<T> list = REIList<T>(T.Class);
REIList 是这样的:
Where REIList is something like this:
public REIList<T>() implements List {
private Object o;
private Class klass;
public REIList(Object o) {
this.o = o;
klass = o.getClass();
}
... the rest of the list implementation ...
并且方法使用Object o和Class klass来获取类型信息.
And the methods use Object o and Class klass to get the type information.
为什么保留通用类信息需要更改语言,而不仅仅是更改 JVM 实现?
Why would preserving generic class information require language changes rather than just a JVM implementation change?
我不明白什么?
推荐答案
重点是,编译器中的具体泛型支持保留类型信息,而类型擦除泛型不支持.AFAIK,首先进行类型擦除的全部意义在于实现向后兼容性(例如,较低版本的 JVM 仍然可以理解泛型类).
The whole point is that reified generics have support in the compiler for preserving type information, whereas type erased generics don't. AFAIK, the whole point of having type erasure in the first place was to enable backwards compatibility (e.g. lower versioned JVMs could still understand generic classes).
您可以像上面那样在实现中显式添加类型信息,但是每次使用列表时都需要额外的代码,而且我认为这很混乱.此外,在这种情况下,除非您自己添加检查,否则您仍然没有对所有列表方法进行运行时类型检查,但是具体化的泛型将确保运行时类型.
You can explicitly add the type information in the implementation, as you have above, but that requires additional code every time the list is used, and is pretty messy in my opinion. Also, in this case, you still don't have runtime type checking for all of the list methods unless you add the checks yourself, however reified generics will ensure the runtime types.
这篇关于什么是具体泛型?它们如何解决类型擦除问题,为什么不进行重大更改就不能添加它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!