Reputation: 3441
My code is like the following :
Class<?> targetClass = Class.forName(class_name);
mthd = targetClass.getDeclaredMethod(function_name, new Class[]{Object.class});
mthd.invoke(new Object()); //fails
why when ever i try to invoke my method IllegalArgumentException
is thrown?
java.lang.IllegalArgumentException
at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
...
what I am missing?
UPDATE: the called function is :
public static String categoryCount(Object val){
System.out.println(val.toString());
return null;
}
Upvotes: 1
Views: 1612
Reputation: 19284
mthd.invoke
needs two arguments in your case.
First is the object to run the invoked method, second is an argument for categoryCount(val)
.
In case of a static method (like you have) use:
mthd.invoke(null, new Object());
For non-static method, use:
mthd.invoke(myObj, new Object());
Upvotes: 3
Reputation: 1052
Class<?> clazz = Class.forName(class_name);
Method method = clazz.getMethod("categoryCount", Object.class);
Object o = method.invoke(null, new Object());
Works fine
Upvotes: 2