通过反射调用变量参数方法

时间:2018-12-09 17:03:53

标签: java reflection

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类有一个testa方法,使用反射来获取此方法并调用它,以上述5种方式,只有最后一种成功,为什么需要通过嵌套数组传递变量参数? / p>

jdk版本是7。

1 个答案:

答案 0 :(得分:3)

public String testa(Object... args)

的语法糖
public String testa(Object[] args)

所以这是一个需要Object数组的方法。

Method.invoke()期望包含所有参数的对象数组传递给方法。因此,如果该方法使用String和Integer,则必须传递包含String和Integer的Object []。由于您的方法采用Object []作为参数,因此必须将包含Object []的Object []传递给Method.invoke()。这就是您上一次尝试所做的。但不是您在其他所有尝试中所做的事情。