在寻找一种优雅的方式来重新抛出异常时,我偶然发现了一个名叫Peter Lawrey的超级黑客answer。 代码如下:
/**
* Cast a CheckedException as an unchecked one.
*
* @param throwable to cast
* @param <T> the type of the Throwable
* @return this method will never return a Throwable instance, it will just throw it.
* @throws T the throwable as an unchecked throwable
*/
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
用法:
} catch(AnyCheckedException e) {
throw rethrow(e);
}
我的问题是:
T
?
我明确地为方法提供了类型参数,IDE建议应该是RuntimeException
。但编译器如何知道呢? RuntimeException
)?