这是我的带有嵌入式评论/问题的示例类。您能否建议处理这种情况的最佳方法?
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>
,但这看起来很难看。有没有更优雅的解决方案?
不幸的是,我的大脑更倾向于 C++ 思维而不是 Java 思维,因此围绕模板与泛型的混淆。我认为这个问题与类型擦除有关,但我不是 100% 确定。