使用反射调用带有数组参数的方法 [英] Invoke method with an array parameter using reflection

查看:108
本文介绍了使用反射调用带有数组参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个方法,通过将一个字符串数组作为参数传递给该方法,从另一个类执行静态方法。

I am attempting to write a method the executes a static method from another class by passing an array of strings as arguments to the method.

这就是我所拥有的:

public static void
executeStaticCommand(final String[] command, Class<?> provider)
{
    Method[] validMethods = provider.getMethods();

    String javaCommand = TextFormat.toCamelCase(command[0]);

    for (Method method : validMethods) {
        if (method.getName().equals(javaCommand)) {
            try {
                method.invoke(null, new Object[] { new Object[] { command } });
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                Throwable ex = e.getCause();
                ex.printStackTrace();
            }
            break;
        }
    }
}

这样:

String[] args = new String[] { "methodName", "arg1", "arg2" }; 
executeStaticCommand(args, ClassName.class);

执行此操作:

public class ClassName {
    public static void methodName(String[] args) {
        assert args[1].equals("arg1");
    }
}

但是我得到 IllegalArgumentException s。

推荐答案

您有两个问题:


  1. 目标参数类型是 String [] ,但是你传入的是 Object []

  2. 您将整个命令数组作为参数传递,其中包含方法名称

  1. The target parameter type is String[], but you're passing in a Object[]
  2. You're passing in the whole command array as arguments, which includes the method name

问题都在内部尝试块中,因此我只显示该代码。

The problems are all in the inner try block, so I show only that code.

String[] args = Arrays.copyOfRange(command, 1, command.length - 1);
method.invoke(null, new Object[]{args}); // must prevent expansion into varargs

感谢 Perception 提醒我varargs问题

Thanks to Perception for reminding me of the varargs issue

这篇关于使用反射调用带有数组参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆