java 使用反射调用具有数组参数的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15951521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invoke method with an array parameter using reflection
提问by azz
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.
我正在尝试编写一个方法,该方法通过将字符串数组作为参数传递给该方法来执行来自另一个类的静态方法。
Here's what I have:
这是我所拥有的:
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;
}
}
}
Such that this:
这样的:
String[] args = new String[] { "methodName", "arg1", "arg2" };
executeStaticCommand(args, ClassName.class);
Should execute this:
应该执行这个:
public class ClassName {
public static void methodName(String[] args) {
assert args[1].equals("arg1");
}
}
However I'm getting IllegalArgumentException
s.
但是我得到了IllegalArgumentException
。
回答by Bohemian
You have two problems:
你有两个问题:
- The target parameter type is
String[]
, but you're passing in aObject[]
- You're passing in the whole command array as arguments, which includes the method name
- 目标参数类型是
String[]
,但您传入的是Object[]
- 您将整个命令数组作为参数传递,其中包括方法名称
The problems are all in the inner try
block, so I show only that code.
问题都在内部try
块中,所以我只展示了那个代码。
String[] args = Arrays.copyOfRange(command, 1, command.length - 1);
method.invoke(null, new Object[]{args}); // must prevent expansion into varargs
Thanks to Perceptionfor reminding me of the varargs issue
感谢Perception提醒我可变参数问题
回答by Lavanya
The method your trying to invoke is expecting String array, however you are passing Object array as param. Change it to String array Or you can pass any type if the method expects Object.
您尝试调用的方法需要 String 数组,但是您将 Object 数组作为参数传递。将其更改为 String 数组,或者如果该方法需要 Object,则您可以传递任何类型。
method.invoke(null,(Object) command );
method.invoke(null,(Object) command );
回答by Zim-Zam O'Pootertoot
Based on this question, it looks like the call should be
基于这个问题,看起来这个电话应该是
method.invoke(null, command);