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.