Java: Passing combination of named and unnamed parameters to executable jar/main method

Tags: , ,



I want to pass, both, named and unnamed arguments to the main method.

Currently I am passing arguments as:

 java -jar myfile.jar param1 param2

and handling them as:

public static void main(String[] args) throws IOException {
    String param1 = args[0];
    String param2 = args[1];
}

However, I want to pass the arguments in a more dynamic way – namely, so that:

  1. I can pass, both, named and unnamed arguments;
  2. I can fetch/handle these arguments with their names;
  3. I will not be required to pass them in the same order, every time I execute the main method.

Passing in a way Something like this:

   java -jar myJar param3name=param3 param2name=param2 param1name=param1 param5 param6

and handling in a way something like this:

public static void main(String[] args) throws IOException {
    //something like
    String param3 = getvaluemethod("param3name");
    String param1 = getvaluemethod("param1name");
     .....
    String param5 = args[n]
    String param6 = args[n+1]
     .....
}

I am fine to work with some external libraries which would make my work easier.

I have already seen this and it is not comprehensive.

Any input on how to accomplish the task?

Answer

Apache Commons CLI is what I use to parse java command line arguments. Examples can be found here and can be used to do any of the following option formats:

  • POSIX like options (ie. tar -zxvf foo.tar.gz)
  • GNU like long options (ie. du --human-readable --max-depth=1)
  • Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
  • Short options with value attached (ie. gcc -O2 foo.c)
  • long options with single hyphen (ie. ant -projecthelp)


Source: stackoverflow