Cast exceptions using type parameters: the right way to do this?

Here is my sample class with inline comments / questions. Could you advise a better way to deal with 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 assume that it will be possible to transfer the reference to Class<? extends Exception> Class<? extends Exception> , but it seems ugly. Is there a more elegant solution?

Unfortunately, my brain is more tightly connected with thinking in C ++ than thinking in Java, hence the confusion surrounding templates against generics. I think this problem is related to type erasure, but I'm not 100% sure.

+4
source share
1 answer

You are trying to recover information such as runtime, so yes, you will need Class.cast or the like. In this case, your code may ClassCastException on the calling getException , because you catch and save all Exception s.

You might be better off removing generics and using caller instanceof or the like.

+2
source

Source: https://habr.com/ru/post/1492477/


All Articles