简体   繁体   中英

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> , but that seems ugly. 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. I think this problem is related to type erasure, but I am not 100% sure.

You are trying to recover runtime type information, so yes you'll need Class.cast or similar. As it stands your code can throw a ClassCastException at the caller of getException because you are catching and storing all Exception s.

You may find it better to remove the generics and have the caller use instanceof or similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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