
扩展接口时,有一种方法可以强制使用自己的类作为参数:
interface I<SELF extends I<SELF>> { SELF getSelf();}class A implements I<A> { A getSelf() { return this; }}class B implements I<A> { // illegal: Bound mismatch A getSelf() { return this; }}编写泛型类时,这甚至可以工作。 唯一的缺点:必须强制转换this
为SELF
。
正如Andrey Makarov在下面的评论中指出的那样,在编写泛型类时,这 无法
可靠地工作。
class A<SELF extends A<SELF>> { SELF getSelf() { return (SELF)this; }}class C extends A<B> {} // Does not fail.// C myC = new C();// B myB = myC.getSelf(); // <-- ClassCastException欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)