编译器如何推断throws中声明的泛型异常类型的类型

时间:2016-12-20 16:19:00

标签: java generics exception-handling

在寻找一种优雅的方式来重新抛出异常时,我偶然发现了一个名叫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);
}

我的问题是:

  1. 编译器如何知道哪个类型是T? 我明确地为方法提供了类型参数,IDE建议应该是RuntimeException。但编译器如何知道呢?
  2. 为什么真正的异常被无阻碍地转换为T(如果编译器将T称为RuntimeException)?

0 个答案:

没有答案