我一直想知道 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
是一个抽象类,如果不继承它就无法调用它的方法,因此在调用它的方法时不会出现任何异常。
关于java - getThis() 技巧和 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31758011/