2016-07-09 11 views
3

Stellen Sie sich eine Methode, wie haben:Finden Sie heraus, was Ausnahmen eine Methode wirft programmatisch

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

Gibt es irgendeine Weise programmatisch die deklarierten geworfen Ausnahmen durch Reflexion zu bekommen?

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

Antwort

6

Sie können getExceptionTypes() Methode verwenden. Sie erhalten Exception[] nicht, da ein solches Array die Ausnahme Instanzen erwarten würde, aber Sie erhalten stattdessen Class<?>[], die alle geworfene Ausnahme .class enthalten wird.

Demo:

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

Ausgang:

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

Sie können, dass die Reflexion api tun.

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

Wenn die Methode Parameter benötigt, müssen Sie sie mit dem Aufruf Class.getMethod() versorgen.

1

Hier ist ein Beispiel:

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

}