vendredi 29 mars 2019

Catch specific exception in java reflection

Given a class with static method and throw some exception

class Foo {
    public static void doThis() throws CannotDoThisException {
        //do something
    }
}

I am using the following reflection to invoke the doThis method

public class Bar {
    Class c = Class.forName("Foo");
    Method m = c.getDeclaredMethod("doThis",null);
    try {
        m.invoke(null,null);
    } catch (CannotDoThisException e) {
       //Compiler says this is unreachable block.
    }
}

How can I catch the exception CannotDoThisException?





Aucun commentaire:

Enregistrer un commentaire