Java 获取此()技巧和ClassCastException
我一直在想Java 获取此()技巧和ClassCastException,java,generics,Java,Generics,我一直在想getThis()技巧,以及不安全强制转换从自绑定类型到其类型参数的替代方法 public abstract class SelfBound<T extends SelfBound<T>> { protected abstract T getThis(); public void doSomething(T instance) { ... } public final void doSomethingWithThis() { doSom
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); }
}
公共抽象类自绑定{
保护抽象T getThis();
公共void doSomething(T实例){…}
public final void doSomething with this(){doSomething(getThis());}
公共最终无效doSomethingWithThisUnsafe(){doSomething((T)this);}
}
是否可以将
SelfBound
子类化,以便doSomethingWithThisUnsafe()
引发类异常
?(在没有子类化自绑定
的情况下是否可以做到这一点?)当然可以通过子类化实现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();
}
}
你说的“没有子类化自绑定”是什么意思还不太清楚。由于自绑定是一个抽象类,如果不将其子类化,则无法调用其方法,因此在调用其方法时不能有任何异常。我不理解您问题的目的。只需返回某个类型的无意义值,该类型不扩展
SelfBound
,但可能已经扩展;返回(SomeSubclass)val在被重写的getThis()
@SotiriosDelimanolis中,他想知道是否有办法选择T
以使dosomethingwhiththis不安全
抛出CCE
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)