简体   繁体   中英

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?

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. 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());
Class<?> clazz = Class.forName(class_name);
Method method = clazz.getMethod("categoryCount", Object.class);
Object o = method.invoke(null, new Object());

Works fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM