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
Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
Find below the code I am trying to execute.
Class from which main method is invoked
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[]:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With