繁体   English   中英

getThis()技巧和ClassCastException

[英]getThis() trick and ClassCastException

我一直想知道getThis()技巧,以及将不安全类型从自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进行子类SelfBound ,以便doSomethingWithThisUnsafe()抛出ClassCastException (是否可以在不SelfBound情况下进行此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是抽象类,因此您不能在不对其进行子类化的情况下调用其方法,因此在调用其方法时不能有任何异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM