ChaosNe0
ChaosNe0

Reputation: 47

How can I invoke a method without knowing the count of parameters using java.lang.reflect?

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

Answers (1)

user4668606
user4668606

Reputation:

No this is not possible. You can invoke the method with a given Object[] as parameters. But there are some constraints on that:

  • the number of parameters must match the number of parameters of the method, so it's not possible to call it with an arbitrary number of parameters. Well, it's possible but you won't get anything except for an exception thrown.
  • the types of the parameters must match the required parameter-types of the method. Same as above, invalid parameter-types lead to an exception.

Luckily both of these are known, thanks to Method#getParameterTypes():

Class<?>[] parameterTypes = someMethod.getParameterTypes();
int parameterCount = parameterTypes.length;

Upvotes: 2

Related Questions