I have the following code snippet which throws exception, the problem seem to be with the parameter which I'm trying to pass to 'foo' method.
public void test() {
try {
Class<?>[] paramType = new Class[] { Object[].class };
Method m = this.getClass().getMethod("foo", paramType);
Object tt = (Object)new String("TEST");
m.invoke(this, new Object[] { tt });
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void foo(Object[] params) {
System.out.println("ffffoooooo" + params);
}
EXCEPTION:
java.lang.IllegalArgumentException: argument type mismatch
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:483)
at reflection.MyReflection.invokeMethod(MyReflection.java:50)
at reflection.MyReflection.main(MyReflection.java:20)
Can some spot my mistake??
The Method.invoke
method takes an Object[]
parameter which corresponds to the arguments you want to provide.
As you've got a single parameter which is of type Object[]
, you need to wrap that in another Object[]
. For example:
m.invoke(this, new Object[] { new Object[] { tt } });
Or you could use the fact that it's a varargs parameter on invoke
:
Object argument = new Object[] { tt };
m.invoke(this, argument);
Note that the compile-time type of argument
being Object
rather than Object[]
is important here, in order to make the compiler create the array due to varargs. If you declare argument
to be of type Object[]
, the compiler won't wrap it in another array.
See more on this question at Stackoverflow