getThis()技巧和ClassCastException

时间:2015-08-01 03:49:52

标签: java generics

我一直想知道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? (是否可以在不继承curl_setopt($ch, CURLOPT_POST, count($post)); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); 的情况下执行此操作?)

1 个答案:

答案 0 :(得分:2)

当然,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&#34;进行子类化,那么你的意思并不明确。由于SelfBound是一个抽象类,因此在不对其进行子类化的情况下无法调用其方法,因此在调用其方法时不能有任何异常。