1
public String testa(Object... args){
    for (Object arg : args) {
        System.out.println(arg);
     }
    return "a";
}

@Test
public void test28() throws InvocationTargetException, IllegalAccessException {
    Method method = ReflectionUtil.getMethodByName(NormalTest.class, "testa");
        //wrong number of arguments
//      method.invoke(this);
        //argument type mismatch
//      method.invoke(this, 123);
        //argument type mismatch
//      method.invoke(this, new Object[]{123});
        // argument type mismatch
//      method.invoke(this, new Object[]{new int[]{123}});
        //right
        method.invoke(this, new Object[]{new Integer[]{123}});
    }

NormalTest class has a testa method, use reflection to get this method and call it, in above 5 ways, only the last is successful, why need to pass variable arguments with nested array?

jdk version is 7.

2
  • I don't think it should be. Object should accept anything at all, so something funky here. Commented Dec 9, 2018 at 17:08
  • Try to create an array of Integer instead and use it Commented Dec 9, 2018 at 17:09

1 Answer 1

3
public String testa(Object... args)

is syntaxic sugar for

public String testa(Object[] args)

So it's a method expecting an Object array.

Method.invoke() expects an array of objects containing all the arguments to pass to the methods. So if the method took a String and an Integer, you would have to pass an Object[] containing a String and an Integer. Since your method takes an Object[] as argument, you must pass, to Method.invoke(), an Object[] containing an Object[]. That's what you're doing in the last attempt. But not what you're doing in every other attempt.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.