简体   繁体   English

尝试调用方法时发生IllegalArgumentException

[英]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.

相关问题 为什么通过Method.Invoke抛出IllegalArgumentException? - Why is IllegalArgumentException thrown here by Method.Invoke? 尝试使用Reflection在私有字段上调用方法时出现NullPointerException - NullPointerException while trying to invoke method on private field using Reflection method.invoke生成IllegalArgumentException:参数数量错误 - method.invoke generates IllegalArgumentException:wrong number of arguments 使用 Java 调用调用方法时出现 IllegalArgumentException - IllegalArgumentException when calling invoke method using Java Reflections Java Method.invoke()抛出IllegalArgumentException:参数类型不匹配 - Java Method.invoke() throwing IllegalArgumentException: argument type mismatch 无法使用Reflection调用main方法 - IllegalArgumentException:参数类型不匹配 - Not able to invoke main method using Reflection - IllegalArgumentException: argument type mismatch 无法调用方法:java.lang.IllegalArgumentException:参数类型不匹配 - Could not invoke method: java.lang.IllegalArgumentException: argument type mismatch 尝试调用方法时出现异常,该方法通过上述 class 的 object 从其他 class 调用方法 - Exception while trying to invoke method, which invokes method from other class through object of said class 创建对象时调用方法 - Invoke method while creating an object ActionListener调用while循环方法 - ActionListener invoke while loop method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM