Reputation: 47
I read a tutorial about java.öang.reflect and found a way to get a method from a class and invoke it with given parameters like that:
Method method = /*some initialization*/;
Object returnValue = method.invoke(null, "parameter-value1");
This calls the static method "method" which takes "parameter-value1" as its only parameter.
Now that's pretty neat, but it is not sufficiently dynamic. I want to invoke a method I only have the method-object of and insert an unspecified number of parameters. Let's say I have Method method
and Object[] parameters
(to be used as parameters for the invocation of method
).
Is it possible to write a short and simple method to call any method with given arguments by using reflect? If so: How to archieve this?
Upvotes: 0
Views: 2339
Reputation:
No this is not possible. You can invoke the method with a given Object[]
as parameters. But there are some constraints on that:
Luckily both of these are known, thanks to Method#getParameterTypes()
:
Class<?>[] parameterTypes = someMethod.getParameterTypes();
int parameterCount = parameterTypes.length;
Upvotes: 2