找出方法以编程方式抛出的异常

kod*_*dai 3 java reflection

想象一下,你有一个像这样的方法:

public void doGreatThings() throws CantDoGreatThingsException, RuntimeException {...}
Run Code Online (Sandbox Code Playgroud)

有没有办法以编程方式通过反射获取声明的抛出异常?

// It might return something like Exception[] thrownExceptions = [CantDoGreatThingsException.class, RuntimeException.class]
Run Code Online (Sandbox Code Playgroud)

Psh*_*emo 7

你可以使用getExceptionTypes()方法.你不会得到,Exception[]因为这样的数组会期望异常实例,但你会得到Class<?>[]它将保留所有抛出的异常.class.

演示:

class Demo{
    private void test() throws IOException, FileAlreadyExistsException{}

    public static void main(java.lang.String[] args) throws Exception {
        Method declaredMethod = Demo.class.getDeclaredMethod("test");
        Class<?>[] exceptionTypes = declaredMethod.getExceptionTypes();
        for (Class<?> exception: exceptionTypes){
            System.out.println(exception);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

class java.io.IOException
class java.nio.file.FileAlreadyExistsException
Run Code Online (Sandbox Code Playgroud)