问题描述
考虑这个例子来自一本书,其中有一个超类Gen和一个子类Gen2 ...
Consider this example taken from a book, with a super class Gen and a subclass Gen2...
class Gen<T> { }
class Gen2<T> extends Gen<T> { }
现在这本书指出下面不会编译(让我们假设它是一个主要方法) p>
Now the book states following will not compile (lets assume its in a main method)
Gen2<Integer> obj = new Gen2<Integer>();
if (obj instanceof Gen2<Integer>) {
//do something
}
由于通用类型信息在运行时不存在,因此无法编译。如果它在运行时不存在,它何时存在?我认为它不会在编译时存在,但会在运行时存在。当然,下面的代码可以在运行时使用通配符...
This can't be compiled because generic type info does not exist at runtime. If it doesn't exist at runtime, when does it exist? I thought that it would not exist at compile time, but would exist at runtime. Certainly, the following works for runtime with a wildcard...
if (obj instanceof Gen<?>) {
//do something else
}
澄清,我的问题是为什么泛型类型信息在运行时不存在?我忽略了一个简单的概念吗?
So to clarify, my question is why does generic type info not exist at runtime? Have I overlooked a simple concept?
推荐答案
问题是泛型并不总是存在于java中(我认为它们添加了1.5)。因此,为了能够实现向后兼容性,输入删除它可以在编译你的代码的同时有效地消除泛型类型信息,以达到这个目的。
The problem is that generics was not always present in java (I think they added it in 1.5). So in order to be able to achieve backwards compatibility there is type erasure which effectively erases generic type information while compiling your code in order to achieve that goal.
摘自相关部分的官方文档:
Excerpt from the relevant parts of the official documentation:
所以这段代码例如
public class Node<T extends Comparable<T>> {
private T data;
private Node<T> next;
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
public T getData() { return data; }
// ...
}
public class Node {
private Comparable data;
private Node next;
public Node(Comparable data, Node next) {
this.data = data;
this.next = next;
}
public Comparable getData() { return data; }
// ...
}
如果您沿着的路径重新生成一些类型信息,就像 lightaber :功能强大但也很危险。
There is a way however to resurrect some of that type information if you tread the path of reflection which is like a lightsaber: powerful but also dangerous.
这篇关于在Java中,为什么在运行时没有泛型类型信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!