这是我的示例类,包含嵌入的注释/问题.能告诉您处理这种情况的最佳方法吗?
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<?扩展Exception>,但这看起来很难看.有更优雅的解决方案吗?
不幸的是,我的大脑比C语言更难以思考,因此围绕模板与泛型的混淆.我认为这个问题与类型擦除有关,但我不是100%肯定.
最佳答案 您正在尝试恢复运行时类型信息,所以是的,您将需要Class.cast或类似信息.现在,您的代码可以在getException的调用者处抛出ClassCastException,因为您正在捕获并存储所有异常.
您可能会发现删除泛型并让调用者使用instanceof或类似的更好.