我一直想知道getThis()
技巧,以及将不安全类型从自限类型转换为其类型参数的替代方法。
public abstract class SelfBound<T extends SelfBound<T>> {
protected abstract T getThis();
public void doSomething(T instance) { ... }
public final void doSomethingWithThis() { doSomething(getThis()); }
public final void doSomethingWithThisUnsafe() { doSomething((T) this); }
}
是否可以对
SelfBound
进行子类化,使doSomethingWithThisUnsafe()
引发ClassCastException
? (是否可以在没有子类SelfBound
的情况下执行此操作?) 最佳答案
当然,可以在子类中包含ClassCastException
。这是一个简单的示例:
public abstract class SelfBound<T extends SelfBound<T>> {
protected abstract T getThis();
public void doSomething(T instance) { }
public final void doSomethingWithThis() { doSomething(getThis()); }
public final void doSomethingWithThisUnsafe() { doSomething((T) this); }
public static class A extends SelfBound<A> {
@Override
protected A getThis() {
return this;
}
}
public static class B extends SelfBound<A> {
@Override
public void doSomething(A instance) {
super.doSomething(instance);
}
@Override
protected A getThis() {
return null;
}
}
public static void main(String[] args) {
new B().doSomethingWithThisUnsafe();
}
}
输出:
Exception in thread "main" java.lang.ClassCastException: SelfBound$B cannot be cast to SelfBound$A
at SelfBound$B.doSomething(SelfBound.java:1)
at SelfBound.doSomethingWithThisUnsafe(SelfBound.java:6)
at SelfBound.main(SelfBound.java:28)
不清楚“没有子类化
SelfBound
”是什么意思。由于SelfBound
是抽象类,因此不能在不对其进行子类化的情况下调用其方法,因此在调用其方法时不能有任何异常。