添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Using method.invoke Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments

Ask Question

I am attempting to invoke a method and return the value; however, I get an IllegalArgumentException: wrong number of arguments

here is the sample code:

public class MyObjAnnoParser {
  public void parse(Class clazz, Object obj) throws ClassNotFoundException, 
        IllegalAccessException, IllegalArgumentException, 
        InvocationTargetException, InstantiationException{
    WatchLogAnno wlAnno= method.getAnnotation(WatchLogAnno.class);
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        if (method.isAnnotationPresent(WatchLogAnno.class)) {
            String info = wlAnno.parentClass(); 
            Class cls = Class.forName(info); 
            //error occurs here -- not sure what it means by wrong number 
            //the obj is wrapped as an Object array as can be seen....
            Object objVal= method.invoke(cls.newInstance(), new Object[]{obj});
            System.out.println(objVal);

Annotation class:

@Target(ElementType.METHOD )
@Retention(RetentionPolicy.RUNTIME)
public @interface WatchLogAnno {
    String parentClass() default "";

MyObj Class:

public class MyObj {
    private String summary;
    @WatchLogAnno(parentClass = "com.stuff.MyObj")
    public String getSummary(){
        return summary;
    public void setSummary(String summary){
        this.summary = summary;

Test class that calls parser:

public class MyObjAnnoParserTest {
    public static void main(String [] args) throws Exception {
        MyObjAnnoParser parser = new MyObjAnnoParser ();
        parser.parse(Annotated.class);
        MyObj myObj = new MyObj();
        myObj.setSummary("Testing an entry for this piece");
        parser.parse(myObj.class, myObj ); 

So, as I listed above in the comments, when I get to the invoke.method call it throws the IllegalArgumentException....

I am sure it is a simple mistake...I appreciate any help...Thanks!

therefore reflection cannot find any method.

Also you create a new object o your class instead of using the supplied one.

Try calling reflection with

Object objVal = method.invoke(obj, new Object[]{});

without any parameter.

right...so if I use method.invoke(cls.newInstance(), new Object[]{}) instead of method.invoke(cls.newInstance(), new Object[]{myObj}), the returned value from getSummary() is null because its not actually access in the instantiated class... – saipanman Jun 6, 2013 at 13:12

doesn't take any parameters (except the implicit this object). However, when invoking the method, you pass one along:

method.invoke(cls.newInstance(), new Object[]{obj});

Either do

method.invoke(cls.newInstance(), new Object[0]);

or define the callee to take a parameter:

@WatchLogAnno(parentClass = "com.stuff.MyObj")
public String getSummary(Object mustBeDeclaredEvenIfNotUsed){
    return summary;

As a third possibility, use reflection to check, how many parameters the method-to-be-called expects, and adjust the parameters accordingly:

 // UNTESTED!
 final Class<?>[] expectedParams = method.getParameterTypes();
 Object[] actualValues;
 if (expectedParams.length == 0) actualValues = new Object[0];
 else if (expectedParams.length == 1) actualValues = new Object[] { obj };
     throw new UnsupportedOperationException("callee has wrong method signature");

If you go this route, then checking, whether the declared argument type is compatible with the actual value might also be a good idea:

 if (!expectedParams[0].isAssignableFrom(obj))
     throw new UnsupportedOperationException("callee's declared parameter type does not match the argument value");
                hmmm... so MyObj class contains a set value of summary. I understand now how I was misusing the invoke method, but still not sure how to acccess the getSummary() method.
– saipanman
                Jun 6, 2013 at 13:10
                well what I mean is the instantiated class MyObj myObj and the value set in summary from getSummary() method...not sure if I am making sense...
– saipanman
                Jun 6, 2013 at 13:15
                thanks...dirk... I had it backwards on the method.invoke... to get the value from getSummary() I had to do method.invoke(obj, new Object[]{});.... thanks again for both... it helps to be able to reflect these questions off someone else...
– saipanman
                Jun 6, 2013 at 13:23
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.