我正在阅读有关 Java 泛型的信息,并且遇到了这个让我有点困惑的话题。
来自:http ://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ205
public abstract class Node <N extends Node<N>> {
private final List<N> children = new ArrayList<N>();
private final N parent;
protected Node(N parent) {
this.parent = parent;
parent.children.add(this); // error: incompatible types
}
public N getParent() {
return parent;
}
public List<N> getChildren() {
return children;
}
}
public class SpecialNode extends Node<SpecialNode> {
public SpecialNode(SpecialNode parent) {
super(parent);
}
}
向下滚动几个屏幕...
public abstract class Node <N extends Node<N>> {
...
protected Node(N parent) {
this.parent = parent;
parent.children.add( (N)this ); // warning: unchecked cast
}
...
}
目标类型为类型参数的强制转换无法在运行时验证并导致未经检查的警告。这种不安全的强制转换引入了意外 ClassCastException 的可能性,最好避免。
有人可以给我一个上面的代码抛出 ClassCastException 的例子吗?
谢谢。