繁体   English   中英

使用泛型类型参数强制转换异常:正确的方法吗?

[英]Casting Exceptions Using Generic Type Parameters: Right way to do it?

这是带有嵌入式注释/问题的示例类。 您能建议解决这种情况的最佳方法吗?

public abstract class AbstractThreadWithException<TException extends Exception>
extends Thread {

    private TException _exception;

    public TException getException() {
        return _exception;
    }

    // I don't like this annotation: SuppressWarnings.  Is there a work-around?
    // I noticed Google Guava code works very hard to avoid these annos.
    @SuppressWarnings("unchecked")
    @Override
    public void run() {
        try {
            runWithException();
        }
        // By Java rules (at least what my compiler says):
        // I cannot catch type TException here.
        catch (Exception e) {
            // This cast requires the SuppressWarnings annotation above.
            _exception = (TException) e;
        }
    }

    public abstract void runWithException()
    throws TException;
}

我想可以传递对Class<? extends Exception>的引用Class<? extends Exception> Class<? extends Exception> ,但这看起来很丑。 还有更优雅的解决方案吗?

不幸的是,与Java思维相比,我的大脑更难与C ++思维联系在一起,因此围绕模板与泛型的混淆。 我认为此问题与类型擦除有关,但我不确定100%。

您正在尝试恢复运行时类型信息,所以是的,您将需要Class.cast或类似的东西。 目前而言,因为您正在捕获并存储所有Exception所以您的代码可以getException的调用方抛出ClassCastException

您可能会发现删除泛型并让调用者使用instanceof或类似方法更好。

暂无
暂无

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

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