我正在阅读有关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的例子吗?
谢谢。