Killrazor
Killrazor

Reputation: 7176

How to getMethod from a variable number of parameters in java reflection

I need to test a java class with a huge number of functions. I'm using cucumber so I could call a function that gets only a parameter or I could call another with 7 or 8 parameters (all of them are string, fortunatelly).

So I make a table like that:

| objectname | funcname  | [varX]             | 
| objectname | funcname2 | [varY]             |
| objectname | funcname3 | [varZ, varX, varY] |
| objectname | funcname  | [varZ]             |

In the code I could convert the third column in a variable list of parameters, that is easy, but my problem is to call the getMethod function. I don't want to define a list of:

objectName.getClass().getMethod("functionName", varList.get(0).getClass());
objectName.getClass().getMethod("functionName", varList.get(0).getClass(), varList.get(1).getClass());
objectName.getClass().getMethod("functionName", varList.get(0).getClass(), varList.get(1).getClass(), varList.get(2).getClass());
....

Is there a way to solve it with something like

objectName.getClass().getMethod("functionName", list2ArgList);

? Something like the c# version of GetMethod public System.Reflection.MethodInfo GetMethod (string name, Type[] types, System.Reflection.ParameterModifier[] modifiers);

Upvotes: 0

Views: 702

Answers (1)

Kayaman
Kayaman

Reputation: 73528

The method you're talking about is Class.getMethod(String name, Class<?>... parameterTypes). Since varargs in Java is just syntactic sugar (for an array), you can do the following

Class[] argList = new Class[] { String.class, String.class };
...getClass().getMethod(methodName, argList);

Now it's up to you to create the argList dynamically, but if you only have Strings as parameters, you only need to get the size right.

Upvotes: 1

Related Questions