javajarcommand-line-argumentsname-value

Making a jar that accepts names and values on command line


Relevant Links:

Java: Passing combination of named and unnamed parameters to executable Jar/Main Method

Passing arguments to JAR which is required by Java Interpreter

I understand how to pass strings from the command line to execute my main method:

java -jar myApp.jar "argument1"

My question is: is it possible to set up my main method in a way that would accept:

java -jar myApp.jar -parameter1 "argument1"

Here is my simple main method for context if you need it

public class myApp {
    public static void main (String[] args){
        System.out.println("Argument1: "+args[0]);
    }
}

Solution

  • Thing is: whatever you pass on the command line goes into that args array. To be precise:

    java xxx -jar JAR yyy
    

    xxx: would be arguments to the JVM itself, like -Dprop:value for properties

    yyy: are passed as arguments to your main method

    So, when you pass "-parameter 'argument1'" then ... that is what you will see inside main!

    In other words: the idea that some command line strings are "arguments"; and other are "-switches", or "--flags", or "-h" shortcuts ... you simply have to write the code to do all of that.

    Luckily, there are plenty of libraries out there that help with that; see enter link description here