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()));
}
}