Reflexivite

Fermé
helloworld95 - 19 nov. 2018 à 18:02
KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 - 19 nov. 2018 à 18:15
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 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015
19 nov. 2018 à 18:15
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