user3103059
user3103059

Reputation:

invoke throws IllegalArgumentException: wrong number of arguments

I know there have been a lot of questions about reflection. I have read every one of them but the answer to my problem doesn't come up.

Here I have the following code

Method fn = Class.forName("paramopt.ParamOpt")
                 .getDeclaredMethod("Fn", double[].class);

The method fn(double[] x) is a function declared on the ParamOpt class as public static. It is invoked this way

 y[n] = (double) fn.invoke(new Object[]{start});

where start is a double array. And there is where I get

IllegalArgumentException: wrong number of arguments message.

Any ideas?

Upvotes: 1

Views: 139

Answers (1)

Andrew
Andrew

Reputation: 49646

public Object invoke(Object obj, Object... args) { ... }

You passed no arguments to the invoke method.

The first parameter is in charge of an instance to invoke this method on. Since the method is static, you should pass null there.

The next parameter is a varargs parameter which presents actual method parameters. Here you go with a double array.


The answer is gonna be:

fn.invoke(null, new Object[]{start});

or simply

fn.invoke(null, start);

According to the javadocs, an IllegalArgumentException is thrown

if the method is an instance method and the specified object argument is not an instance of the class or interface declaring the underlying method (or of a subclass or implementor thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion.


In addition, "15.12.4.4 Locate Method to Invoke" might be helpful.

Upvotes: 1

Related Questions