John Keyes Creating a command line parser

The newParser method on CommandLineParserFactory is used to create command line parser instances.

// create a command line parser CommandLineParser parser = CommandLineParserFactory.newParser();

Different applications may require different parsing implementation strategies. CLI ships with two implementations: PosixParser and GnuParser. Both of these implement the CommandLineParser interface.

The parser implementation is specified using the org.apache.commons.cli.parser system property. This is set to be the PosixParser by default.

// parser is a PosixParser CommandLineParser parser = CommandLineParserFactory.newParser(); // configure CLI to use the GNU Parser System.setProperty( "org.apache.commons.cli.parser", "org.apache.commons.cli.GnuParser" ); // parser is a GnuParser parser = CommandLineParserFactory.newParser(); // configure CLI to use the Posix Parser System.setProperty( "org.apache.commons.cli.parser", "org.apache.commons.cli.PosixParser" ); // parser is a PosixParser parser = CommandLineParserFactory.newParser();

Now that a parser has been created the command line tokens can be parsed. The two parse methods on CommandLineParser perform this task.

public static void main( String[] args ) { // create the options Options options = ...; // create the parser CommandLine parser = ...; // parse the command line tokens CommandLine cmd = parser.parse( options, args ); }