Store mutually exclusive Option
objects in an OptionGroup
, and add
this OptionGroup
to an Options
object using the addOptionGroup( )
method. Assume you are
working with the following program argument specification: -h
, -v
,
and
-f
<filename>
|
-m
<email>
. -h
and
-v
are both optional and only one of
-f
or -m
can be specified. If both -m
and -f
are supplied as program arguments, an exception is thrown. In the
following example, the -f
and
-m
options are added to an OptionGroup
, which is then added to the
Options
object used to parse the
program arguments:
import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.CommandLine; public static void main(String[] args) throws Exception { // Create a Parser CommandLineParser parser = new BasicParser( ); Options options = new Options( ); options.addOption("h", "help", false, "Print this usage information"); options.addOption("v", "verbose", false, "Print out VERBOSE information" ); OptionGroup optionGroup = new OptionGroup( ); optionGroup.addOption( OptionBuilder.hasArg(true).create('f') ); optionGroup.addOption( OptionBuilder.hasArg(true).create('m') ); options.addOptionGroup( optionGroup ); // Parse the program arguments CommandLine commandLine = parser.parse( options, args ); // ... do important stuff ... }
If the user supplies both -f
and -m
at the same time, the CommandLineParser
will throw an AlreadySelectedException
.
In the Solution, the -f
and
-m
options were created using the
OptionBuilder
class. This utility
lets you build an Option
object by
chaining a series of method calls. For example, the following code
creates a required option, "b," which takes an argument:
Option option = OptionBuilder.hasArgs(true).isRequired(true).create('b');
OptionGroup
objects are a good
way to enforce the structure of command-line options. If you were
parsing the command line with a StringTokenizer
and keeping track of all of
the specified options that may or may not have parameters, this could
involve 30 or 40 lines of code just to manage this validation process.
By using Commons CLI, you delegate this complexity and cut down on the
amount of code you need to maintain.
What happens if a user specifies two options from an OptionGroup
? Does the application just fail
catastrophically from a RuntimeException
? Usually, if a program has a
problem parsing command-line arguments, it will print out a helpful
usage message. "Printing Usage Information" demonstrates the use of CLI
to automatically create a usage message.