我不理解 Reflection API 方法类中 getGenericExceptionTypes
和 getExceptionTypes
方法之间的区别,尤其是在 java 中不允许在创建通用异常时使用前者...
例如,
GenericException<T> extends Throwable{ /// NOT ALLOWED
}
最佳答案
举个例子
public class Example {
public static void main(String[] args) throws Exception {
Method m = Example.class.getMethod("method");
System.out.println(m.getGenericExceptionTypes()[0]);
System.out.println(m.getExceptionTypes()[0]);
}
public static <T extends Throwable> void method() throws T {}
}
打印
T
class java.lang.Throwable
作为 Method#getGenericExceptionTypes()
的 Javadoc州
If an exception type is a type variable or a parameterized type, it is created.
这就是返回的内容。
同样,
public class Example<T extends Throwable> {
public static void main(String[] args) throws Exception {
Method m = Example.class.getMethod("method");
System.out.println(m.getGenericExceptionTypes()[0]);
System.out.println(m.getExceptionTypes()[0]);
}
public void method() throws T {}
}
会有相同的输出。
因此,虽然您不能创建 Throwable
的泛型子类型,但您可以创建一个以 Throwable
(或其子类型)作为其绑定(bind)的泛型类型变量。
关于java - getGenericExceptionTypes 和 getExceptionTypes 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24968386/