Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 找出方法以编程方式抛出的异常_Java_Reflection - Fatal编程技术网

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

Java 找出方法以编程方式抛出的异常,java,reflection,Java,Reflection,假设您有一种方法,如: public void doGreatThings() throws CantDoGreatThingsException, RuntimeException {...} 是否有任何方法可以通过反射以编程方式获取已声明的抛出异常 // It might return something like Exception[] thrownExceptions = [CantDoGreatThingsException.class, RuntimeException.class

假设您有一种方法,如:

public void doGreatThings() throws CantDoGreatThingsException, RuntimeException {...}
是否有任何方法可以通过反射以编程方式获取已声明的抛出异常

// It might return something like Exception[] thrownExceptions = [CantDoGreatThingsException.class, RuntimeException.class]
你可以使用这个方法。您将不会得到
Exception[]
,因为这样的数组需要异常实例,但您将得到
Class[]
,它将保存所有抛出的异常
.Class

演示:


您可以通过反射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()));
    }

}
// First resolve the method
Method method = MyClass.class.getMethod("doGreatThings");
// Retrieve the Exceptions from the method
System.out.println(Arrays.toString(method.getExceptionTypes()));
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()));
    }

}