aib aib - 4 months ago 16
Java Question

Apache Commons CLI - option type and default value

How can I give a CLI Option a type - such as

? (Later, how can I get the parsed value with a single function call?)

How can I give a CLI Option a default value? Such that
or the function call mentioned above return that value unless one is specified on the command line?


EDIT: Default values are now supported. See answer below.

As Brent Worden already mentioned, default values are not supported.

I had issues with using Option.setType too. I always got a null pointer exception when calling getParsedOptionValue on an option with type Integer.class. Because the documentation was not really helpful I looked into the source code.

Looking at the TypeHandler class and the PatternOptionBuilder class you can see that Number.class must be used for int or Integer.

And here is a simple example:

CommandLineParser cmdLineParser = new PosixParser();

Options options = new Options();

try {
    CommandLine cmdLine = cmdLineParser.parse(options, args);

    int value = 0; // initialize to some meaningful default value
    if (cmdLine.hasOption("integer-option")) {
        value = ((Number)cmdLine.getParsedOptionValue("integer-option")).intValue();

} catch (ParseException e) {

Keep in mind that value can overflow if a number is provided which does not fit into an int.