はあなたのようなメソッドを持っている想像スローどのような例外を見つけますか?方法は、プログラム
// It might return something like Exception[] thrownExceptions = [CantDoGreatThingsException.class, RuntimeException.class]
はあなたのようなメソッドを持っている想像スローどのような例外を見つけますか?方法は、プログラム
// 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()));
}
}