java - getThis() 技巧和 ClassCastException

标签 java generics

我一直想知道 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/

相关文章:

java - 使用udp发送实时语音

Java spring application.properties 值没有被应用程序使用

java - Guice AssistedInject 不会注入(inject)工厂

java - 子类化和泛型

java.security.cert.CertificateException : Certificates does not conform to algorithm constraints

java - Jslider 增长和收缩图标

java - 设计模式 : Lazy Singleton, 泛型和继承 : java. lang.Class 无法转换为 java.lang.reflect.ParameterizedType

delphi - 有没有办法从通用约束类型获取 GUID?

泛型和 Xstream

generics - 泛型类型的 WebApi2 ResponseType 属性