Reflexivite

helloworld95 -  
KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   -
Bonjour,

Comment puis-je recupérer un throws Exception d'une methode en reflexivité ?

Merci



Configuration: Windows / Chrome 70.0.3538.102

1 réponse

KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   3 020
 
Bonjour,

Il faut faire un try/catch sur une InvocationTargetException et récupérer l'exception au travers de la méthode getCause (ou getTargetException).

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/InvocationTargetException.html

Exemple :

import java.lang.reflect.InvocationTargetException;

public class Test {

    public static void f() {
        throw new IllegalStateException("hello");
    }

    public static void main(String[] args) throws Exception {
        try {
            Test.class.getMethod("f").invoke(null);
        } catch (InvocationTargetException e) {
            System.err.println(e.getCause()); // java.lang.IllegalStateException: hello
        }
    }
}
0