简体   繁体   中英

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM