简体   繁体   English

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

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

Here is my sample class with embedded comments/questions. 这是带有嵌入式注释/问题的示例类。 Can you please advise the best way to handle this situation? 您能建议解决这种情况的最佳方法吗?

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;
}

I suppose it would be possible to pass a reference to Class<? extends Exception> 我想可以传递对Class<? extends Exception>的引用Class<? extends Exception> Class<? extends Exception> , but that seems ugly. Class<? extends Exception> ,但这看起来很丑。 Is there a more graceful solution? 还有更优雅的解决方案吗?

Unfortunately, my brain is more hard-wired to C++ thinking than Java thinking, hence the confusion surrounding templates vs. generics. 不幸的是,与Java思维相比,我的大脑更难与C ++思维联系在一起,因此围绕模板与泛型的混淆。 I think this problem is related to type erasure, but I am not 100% sure. 我认为此问题与类型擦除有关,但我不确定100%。

You are trying to recover runtime type information, so yes you'll need Class.cast or similar. 您正在尝试恢复运行时类型信息,所以是的,您将需要Class.cast或类似的东西。 As it stands your code can throw a ClassCastException at the caller of getException because you are catching and storing all Exception s. 目前而言,因为您正在捕获并存储所有Exception所以您的代码可以getException的调用方抛出ClassCastException

You may find it better to remove the generics and have the caller use instanceof or similar. 您可能会发现删除泛型并让调用者使用instanceof或类似方法更好。

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

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