Apache Commons CLI - Overview


Advertisements

The Apache Commons CLI are the components of the Apache Commons which are derived from Java API and provides an API to parse command line arguments/options passed to the programs. This API also enables to print help related to options available.

Command line processing comprises of three stages.

  • Definition Stage
  • Parsing Stage
  • Interrogation Stage

Definition Stage

In definition stage, we define the options that application can take and act accordingly. Commons CLI provides Options class which is a container for Option objects.

// create Options object
Options options = new Options();

// add a option
options.addOption("a", false, "add two numbers");

Here we've added an option flag a, while false as second parameter signifies that option is not mandatory and third parameter states the description of option.

Parsing Stage

In parsing stage, we parse the options passed using command line arguments after creating a parser instance.

//Create a parser
CommandLineParser parser = new DefaultParser();

//parse the options passed as command line arguments
CommandLine cmd = parser.parse( options, args);

Interrogation Stage

In Interrogation stage, we check if a particular option is present or not and process the command accordingly.

//hasOptions checks if option is present or not
if(cmd.hasOption("a")) {
   // add the two numbers
} else if(cmd.hasOption("m")) {
   // multiply the two numbers
}
Advertisements