views:

33

answers:

1

I'm getting my feet wet with the Apache Commons CLI library for command-line parsing. It works fine for String-valued options, but I'm not sure how to cleanly handle boolean-valued command-line flags. I've tried this:

    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption(new Option("parseOnly", "Only parse"));
    CommandLine cl = parser.parse( options, args );

    if( cl.hasOption( "parseOnly" ) )
    PARSE_ONLY = (Boolean) cl.getParsedOptionValue( "parseOnly" );

But this fails with a NullPointerException on the file line, because cl.getParsedOptionValue() returns null and that can't be cast to Boolean.

cl.hasOption( "parseOnly" ) returns true or false, but it's not clear from the docs what that means - does it mean the user specified it and it could be either true or false? Or does it mean the flag is activated? What if you want a flag to be default true, and let the user turn it off (like --noParseOnly in other getopt parsers)?

I'll appreciate any suggestions people have, including RTFMs - I'm sure this is well-trodden ground. Thanks.

A: 

For boolean options (or flags), if the option is found then the option value is true, otherwise the value is false.

Therefore, if a user specifies -parseOnly, then that means that it is true. If -parseOnly is not present, then the user does not want it and it is false.

So all you need to do is:

 if( cl.hasOption( "parseOnly" ) ){
    //do something
 }

Another point: Don't cast a string to boolean. Instead, use Boolean.valueOf(cl.getOptionValue("parseOnly")) to convert a String to boolean.

dogbane
In that case, how do I handle an option with default value true, which I want the caller to be able to turn off? Make a separate `noParseOnly` option (but then I quickly run out of single-letter abbreviations)? Let it take a value like `--parseOnly=0` (but then the processing gets more complicated)? Not sure.
Ken Williams
Regarding `Boolean.valueOf()` - see my comment above, `getParsedOptionValue()` returns an Object (of unknown type), not a String.
Ken Williams
use getOptionValue() which returns a string, instead of getParsedOptionValue().
dogbane