获取异常原因并转换为正确类型的正确方法签名是什么?
What's the correct method signature for getting the cause of an exception, typecast to the correct type?
我有一个方法 getInstanceOfCause() 接受一个异常 class 和一个 Throwable,遍历 Throwable 的原因及其原因和 returns 与 class 作为第一个参数传递。它看起来像这样:
public class ExceptionUtil {
public static <T> T getInstanceOfCause(Class<? extends Throwable> expected, Throwable exc) {
return (expected.isInstance(exc)) ? (T) exc : getInstanceOfCause(expected, exc.getCause());
}
}
让我们假设预期的类型确实在 "cause-chain" 中并且调用不会导致 NPE。我可以这样使用它:
MyException myException = ExceptionUtil.<MyException>getInstanceOfCause(MyException.class, exception);
这很尴尬,因为我必须指定两次类型。有什么方法可以重写方法签名,以便我可以像下面那样使用它,同时仍然确保在编译时该类型是 Throwable 的 subclass?
MyException myException = ExceptionUtil.getInstanceOfCause(MyException.class, exception);
或
MyException myException = ExceptionUtil.<MyException>getInstanceOfCause(exception);
请注意,T
可以 从您当前的方法签名中推断出来。一个问题是你可以这样称呼它:
Foo foo = ExceptionUtil.getInstanceOfCause(MyException.class, exception);
这毫无意义。
我猜你想保证第一个参数的return值类型和class的类型是一样的?
您可以使用通用参数 T
:
public static <T extends Throwable> T getInstanceOfCause(Class<T> expected, Throwable exc) {
return (expected.isInstance(exc)) ? (T) exc : getInstanceOfCause(expected, exc.getCause());
}
请注意我如何将 T
限制为 Throwable
,并在 Class<T> expected
和 return 值类型中使用它。这保证 return 值类型与传入的 class 类型相同。
我有一个方法 getInstanceOfCause() 接受一个异常 class 和一个 Throwable,遍历 Throwable 的原因及其原因和 returns 与 class 作为第一个参数传递。它看起来像这样:
public class ExceptionUtil {
public static <T> T getInstanceOfCause(Class<? extends Throwable> expected, Throwable exc) {
return (expected.isInstance(exc)) ? (T) exc : getInstanceOfCause(expected, exc.getCause());
}
}
让我们假设预期的类型确实在 "cause-chain" 中并且调用不会导致 NPE。我可以这样使用它:
MyException myException = ExceptionUtil.<MyException>getInstanceOfCause(MyException.class, exception);
这很尴尬,因为我必须指定两次类型。有什么方法可以重写方法签名,以便我可以像下面那样使用它,同时仍然确保在编译时该类型是 Throwable 的 subclass?
MyException myException = ExceptionUtil.getInstanceOfCause(MyException.class, exception);
或
MyException myException = ExceptionUtil.<MyException>getInstanceOfCause(exception);
请注意,T
可以 从您当前的方法签名中推断出来。一个问题是你可以这样称呼它:
Foo foo = ExceptionUtil.getInstanceOfCause(MyException.class, exception);
这毫无意义。
我猜你想保证第一个参数的return值类型和class的类型是一样的?
您可以使用通用参数 T
:
public static <T extends Throwable> T getInstanceOfCause(Class<T> expected, Throwable exc) {
return (expected.isInstance(exc)) ? (T) exc : getInstanceOfCause(expected, exc.getCause());
}
请注意我如何将 T
限制为 Throwable
,并在 Class<T> expected
和 return 值类型中使用它。这保证 return 值类型与传入的 class 类型相同。