Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java boolean CLI options

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.

like image 908
Ken Williams Avatar asked Sep 15 '10 21:09

Ken Williams


1 Answers

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.

like image 75
dogbane Avatar answered Oct 12 '22 22:10

dogbane