lundi 4 septembre 2017

How to pass an array instead of variable arguments in java?

I want to pass an array instead of variable arguments to a java method. In similar questions people had answered that arrays are no different than ellipses so it must work. but it doesn't work for me. Here is my coed:

String[] parameters = text.split("[?]");
Object[] params = Arrays.asList(parameters).toArray(new Object[parameters.length]);
params[0] = myObject;
method.invoke(params)

Where text is smth like: myMethod?param1?param2 ... But it can also be smth like myMethod in case the method has no arguments.

java.lang.IllegalArgumentException: wrong number of arguments at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497)

What should I do?





Aucun commentaire:

Enregistrer un commentaire