java - getGenericExceptionTypes 和 getExceptionTypes 之间的区别

标签 java exception generics reflection

我不理解 Reflection API 方法类中 getGenericExceptionTypesgetExceptionTypes 方法之间的区别,尤其是在 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/

相关文章:

java - @JsonPropertyOrder 和来自父类(super class)的字段

java - Delphi/Android 在哪里搜索本地语言库?

exception - WinCE 5.0 上 Microsoft.AGL.Common.MISC.HandleAr() 的 System.Exception

c++ - Google 测试和 std::vector 范围异常

generics - 如何从 Dart/Flutter 中的泛型函数调用命名构造函数

java - MySQL 冗余外键

: Random number generation of 14 positive digits

c# - 来自线程的异常不会冒泡到主线程

scala - 对两种类型之间的二元关系建模

c# - LightInject 不解析继承的泛型类型