繁体   English   中英

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

[英]Find out what exceptions a method throws programmatically

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

public void doGreatThings() throws CantDoGreatThingsException, RuntimeException {...}

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

// It might return something like Exception[] thrownExceptions = [CantDoGreatThingsException.class, RuntimeException.class]

您可以使用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);
        }
    }
}

输出:

class java.io.IOException
class java.nio.file.FileAlreadyExistsException

你可以做反射api。

// First resolve the method
Method method = MyClass.class.getMethod("doGreatThings");
// Retrieve the Exceptions from the method
System.out.println(Arrays.toString(method.getExceptionTypes()));

如果方法需要参数,则需要使用Class.getMethod()调用。

这是一个例子:

import java.io.IOException;
import java.util.Arrays;

public class Test {

    public void test() throws RuntimeException, IOException {

    }

    public static void main(String[] args) throws NoSuchMethodException, SecurityException {
        System.out.println(Arrays.toString(Test.class.getDeclaredMethod("test").getExceptionTypes()));
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM