java - GetMethod and invoke it via Reflection passing Object[] as param -
i have following code snippet throws exception, problem seem parameter i'm trying pass '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 @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:483) @ reflection.myreflection.invokemethod(myreflection.java:50) @ reflection.myreflection.main(myreflection.java:20) can spot mistake??
the method.invoke method takes object[] parameter corresponds arguments want provide.
as you've got single parameter of type object[], need wrap in another object[]. example:
m.invoke(this, new object[] { new object[] { tt } }); or use fact it's varargs parameter on invoke:
object argument = new object[] { tt }; m.invoke(this, argument); note compile-time type of argument being object rather object[] important here, in order make compiler create array due varargs. if declare argument of type object[], compiler won't wrap in array.
Comments
Post a Comment