[英]IllegalArgumentException while trying to invoke method
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? 为什么我什么时候尝试调用我的方法
IllegalArgumentException
?
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;
}
mthd.invoke
needs two arguments in your case. 在您的情况下,
mthd.invoke
需要两个参数。 First is the object to run the invoked method, second is an argument for categoryCount(val)
. 首先是运行调用方法的对象,其次是
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());
Class<?> clazz = Class.forName(class_name);
Method method = clazz.getMethod("categoryCount", Object.class);
Object o = method.invoke(null, new Object());
Works fine 工作正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.