[英]Not able to invoke main method using Reflection - IllegalArgumentException: argument type mismatch
I am writing a sample application for learning reflection. 我正在编写一个学习反思的示例应用程序。 I am trying to invoke the main method define in one class from another class using reflection but i am getting 我试图使用反射从另一个类调用一个类中的main方法,但我得到了
Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch 线程“main”中的异常java.lang.IllegalArgumentException:参数类型不匹配
Find below the code I am trying to execute. 在下面找到我想要执行的代码。
Class from which main method is invoked 从中调用main方法的类
import java.lang.reflect.Method;
public class Invoker {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.nagpal.invokemainmethod.Invoked");
Method method = clazz.getMethod("main", new Class[] { String[].class });
Object[] params = new Object[4];
params[0] = "arg 1";
params[1] = "arg 2";
params[2] = "arg 3";
params[3] = "arg 4";
method.invoke(null, new Object[] { params });
}
Class whose main method is to be invoked 要调用其主要方法的类
public class Invoked {
public static void main(String[] args) {
if (args.length < 3) {
throw new IllegalArgumentException();
}
for (int i = 0; i < args.length; i++) {
System.out.println("args[" + args[i] + "]");
}
}
}
You are almost there: the type of the params
should be String[]
, not Object[]
: 你几乎就在那里: params
的类型应该是String[]
,而不是Object[]
:
String[] params = new String[4];
params[0] = "arg 1";
params[1] = "arg 2";
params[2] = "arg 3";
params[3] = "arg 4";
Trying to pass Object[]
to main(String[])
causes the error that you see. 尝试将Object[]
传递给main(String[])
会导致您看到的错误。
The method signature is String[]
but the runtime-type of params
is Object[]
. 方法签名是String[]
但params
的运行时类型是Object[]
。 Try: 尝试:
Object[] params = new String[4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.