Reputation: 1163
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?
Upvotes: 2
Views: 161
Reputation: 29710
varargs are passed as an array, so you must create this array like in:
var args = Arrays.asList(arg1, ...).toArray()
or
var args = List.of(arg1, ...).toArray()
or even create a method, eventually the one you are already writing, receiving the varargs
void method(Object... args) {
...
All the above options having the method invoked like
method.invoke(instance, args);
it all depends on the whole context
Varargs are (almost) treated as arrays, that is, type... args
is the same as type[] args
inside the method, the compiler just convert the arguments to an array when calling such a method.
Upvotes: 2
Reputation: 49646
Collect arg0
, arg1
, argsN
into an Object[]
array, truncate the size to numberOfArguments
and pass it:
Object[] args = {arg0, arg1, ..., argsN};
method.invoke(clazzInstance, Arrays.copyOfRange(args, 0, numberOfArguments));
Upvotes: 3
Reputation: 967
if the method that you are invoking accept variable number of args of the same type, like
method(type...arg)
you can just use an array as a parameter
method.invoke(clazzInstance, arg[])
If the arguments are of different type I don't advise you to do a method like method(Object[]...obj) because you don't put any restriction on the types that the method have to work with, and this can lead to some error devolping the code
Upvotes: 0