[ACCEPTED]-Apache Commons CLI - option type and default value-apache-commons-cli
EDIT: Default values are now supported. See answer https://stackoverflow.com/a/14309108/1082541 below.
As Brent Worden already mentioned, default 10 values are not supported.
I had issues with 9 using Option.setType
too. I always got a null pointer 8 exception when calling getParsedOptionValue
on an option with 7 type Integer.class
. Because the documentation was not 6 really helpful I looked into the source 5 code.
Looking at the TypeHandler class and the PatternOptionBuilder class 4 you can see that Number.class
must be used for int
or Integer
.
And 3 here is a simple example:
CommandLineParser cmdLineParser = new PosixParser();
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("integer-option")
.withDescription("description")
.withType(Number.class)
.hasArg()
.withArgName("argname")
.create());
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();
}
System.out.println(value);
} catch (ParseException e) {
e.printStackTrace();
}
Keep in mind that 2 value
can overflow if a number is provided which 1 does not fit into an int
.
I do not know if not working or if added 2 recently but getOptionValue() has an overloaded version that 1 accepts a default (String) value
The OptionBuilder is deprecated in version 8 1.3 & 1.4 and Option.Builder
doesn't seem to have 7 a direct function to set the type. There 6 is a function for the Option
class called setType
. You 5 can a retrieve a converted value with the 4 function CommandLine.getParsedOptionValue
.
Not sure why it's not part of 3 the builder anymore. It requires some code 2 like this now:
options = new Options();
Option minOpt = Option.builder("min").hasArg().build();
minOpt.setType(Number.class);
options.addOption(minOpt);
and reading it:
String testInput = "-min 14";
String[] splitInput = testInput.split("\\s+");
CommandLine cmd = CLparser.parse(options, splitInput);
System.out.println(cmd.getParsedOptionValue("min"));
which would 1 give a variable of type Long
CLI does not support default values. Any 4 unset option results in getOptionValue
returning null
.
You 3 can specify option types using the Option.setType method 2 and extract the parsed option value as that 1 type using CommandLine.getParsedOptionValue
One can use other definition of
getOptionValue:
public String getOptionValue(String opt, String defaultValue)
and wrap 2 your default value to string.
Example:
String checkbox = line.getOptionValue("cb", String.valueOf(false));
output: false
it 1 worked for me
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.