Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] + "]");
    }
  }

  }
like image 965
Bagira Avatar asked Mar 27 '26 20:03

Bagira


1 Answers

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.

like image 156
Sergey Kalinichenko Avatar answered Mar 29 '26 08:03

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!