首页 文章

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

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

jdk版本是7 .

1 回答

  • 3
    public String testa(Object... args)
    

    是语法糖

    public String testa(Object[] args)
    

    所以这是一个期待Object数组的方法 .

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

相关问题