2016-07-09 3 views
3

はあなたのようなメソッドを持っている想像スローどのような例外を見つけますか?方法は、プログラム

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

答えて

6

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 
1

あなたはそのリフレクション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()呼び出しを指定する必要があります。

1

ここに例を示します。

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

} 
関連する問題