jeudi 21 mars 2019

Is there a non-exception way to access getDeclaredMethod?

I have two objects I might need to invoke methods on, and I won't know which one it belongs to coming in. Right now, my basic workflow is thus:

Method method = null;
Target target = null;
try {
    method = first.getClass().getDeclaredMethod(methodName, typeParams);
    target = first;
} catch(NoSuchMethodException e) { 
    try {
        method = second.getClass().getDeclaredMethod(methodName, typeParams);
        target = second;
    } catch(NoSuchMethodException e1) {
        // they sent us a bad command, return 404-esque response
    }
}
method.invoke(target, arguments);

I would really like to avoid all the exception handling like this, because not having a method isn't really an exception, it's an expectation. The ideal would be

if(first.getClass().hasDeclaredMethod(methodName, typeParams)) {
    return first.getClass().getDeclaredMethod(methodName, typeParams).invoke(first, arguments); 
}
if(second.getClass().hasDeclaredMethod(methodName, typeParams)) {
    return second.getClass().getDeclaredMethod(methodName, typeParams).invoke(second, arguments); 
}
// they sent us a bad command, return 404-esque response

What sorts of options are available to reduce the dependency on exceptions in this way? I'd prefer to not write "wrapper methods", as those can be cumbersome and difficult to tell when an error occurred or not.





Aucun commentaire:

Enregistrer un commentaire