mum mum - 1 year ago 55
Java Question

how to pass command line arguments to main method dynamically

I am passing my main class as a command line argument to launch VM

Now i need to pass command line arguments to that main class

Is there any way to do this?

this is the way i am doing it

VirtualMachineManager manager = Bootstrap.virtualMachineManager();
LaunchingConnector connector = manager.defaultConnector();
Map arguments = connector.defaultArguments();

here userVMargs is classpath of my main class and the also classpath of the class which is being used to invoke the method of class inside my main class

and cmdLine is having my main class along with the class and its function
and i am using eclipse as IDE to develop my project


If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.

Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3

The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.

Consider a program

package test;


    public class ArgsTest {

        public static void main(String[] args) throws IOException {

            System.out.println("Program Arguments:");
            for (String arg : args) {
                System.out.println("\t" + arg);

            System.out.println("System Properties from VM Arguments");
            String sysProp1 = "sysProp1";
            System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
            String sysProp2 = "sysProp2";
            System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));


If given input as,

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3 

in the commandline, in project bin folder would give the following result:

Program Arguments:
System Properties from VM Arguments
  Name:sysProp1, Value:sp1
  Name:sysProp2, Value:sp2