我有一个方法getInstanceOfCause(),它接受一个异常类和一个Throwable方法,遍历Throwable的原因及其原因,并返回与作为第一个参数传递的类匹配的cause的实例。看起来像这样:
public class ExceptionUtil {
public static <T> T getInstanceOfCause(Class<? extends Throwable> expected, Throwable exc) {
return (expected.isInstance(exc)) ? (T) exc : getInstanceOfCause(expected, exc.getCause());
}
}
假设期望的类型确实在“原因链”中,并且该调用不会引起NPE。我可以这样使用:
MyException myException = ExceptionUtil.<MyException>getInstanceOfCause(MyException.class, exception);
这很尴尬,因为我必须两次指定类型。有什么方法可以重写方法签名,以便我可以像下面一样使用它,同时仍在编译时确保类型是Throwable的子类?
MyException myException = ExceptionUtil.getInstanceOfCause(MyException.class, exception);
或者
MyException myException = ExceptionUtil.<MyException>getInstanceOfCause(exception);
明月笑刀无情
相关分类