【发布时间】:2019-07-06 17:13:01
【问题描述】:
假设我有这个代码:
class A<THIS extends A> {
public THIS self() {
return (THIS) this;
}
}
class B extends A<B> { }
A a = new A<>().self().self().self(); // OK
B b = new B().self().self().self().self().self().self(); // OK
它编译得很好。 但是当我再添加一个继承级别时,它就不起作用了。
class A<THIS extends A> {
public THIS self() {
return (THIS) this;
}
}
class B<THIS extends B> extends A<B> { }
class C extends B<C> { }
A<A> self2 = new A<A>().self().self().self(); // OK
B<B> self = new B<B>().self().self().self().self(); // error -> A
C self1 = new C().self().self(); // error -> A
我尝试了不同的泛型类型,但没有任何帮助。
我必须做什么才能编译这段代码?
【问题讨论】:
-
您正在为
self使用原始类型。见:stackoverflow.com/questions/2770321/… -
这种方法是有缺陷的。极端情况:
class D extends A<B> {}编译,但new D().self().getClass()将抛出ClassCastException。
标签: java generics inheritance self-reference