mardi 9 octobre 2018

java.reflection: How can I do method.invoke(clazz, varargs) with dynamic number of args?

I want to do method calls using reflection via method.invoke(clazz, varargs) with varying number of arguments and realize this way the call of different methods with one call only and not via explicit, hard coded number of arguments. In the moment I do the following:

... 
determine method arguments via reflection
...
if (numberOfArguments == 0) {
    method.invoke(clazzInstance, null);
} else if (numberOfArguments == 1) {
    method.invoke(clazzInstance, arg0);
} else if (numberOfArguments == 2) {
    method.invoke(clazzInstance, arg0, arg1);
} ... etc

is there a way to do this more elegantly without the need for explicitly checking for the number of arguments?





Aucun commentaire:

Enregistrer un commentaire