mercredi 19 février 2020

Using reflection instead of a long switch statement

Hey so I have a pretty long switch statement that calls a method based on a string like so

private void callMethod(String name) {
    switch(name) {
        case "blah":
            blah();
            break;
        case "method":
            method()
            break;
    }
}

etc.

So I used reflection to shorten the code

try {
    Method method = ClassName.class.getDeclaredMethod(name, args);
    method.invoke(args);
} catch (NoSuchMethodException e) {
    // switch default
}

Just wondering if using reflection like this is bad on memory/performance. I only call this function every so often.





Aucun commentaire:

Enregistrer un commentaire