aib*_*aib 36 java apache-commons apache-commons-cli
如何为CLI选项提供类型 - 例如int或Integer?(稍后,如何通过单个函数调用获取解析后的值?)
如何为CLI Option提供默认值?这样CommandLine.getOptionValue()或上面提到的函数调用返回该值,除非在命令行中指定了一个值?
小智 47
编辑:现在支持默认值.请参阅下面的答案/sf/answers/1001637591/.
正如Brent Worden已经提到的,不支持默认值.
我也有使用问题Option.setType.在调用getParsedOptionValue带有类型的选项时,我总是得到一个空指针异常Integer.class.因为文档不是真的有用,所以我查看了源代码.
纵观类型处理器类和PatternOptionBuilder类,你可以看到,Number.class必须用于int或Integer.
这是一个简单的例子:
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();
}
Run Code Online (Sandbox Code Playgroud)
请记住,value如果提供的数字不适合,则会溢出int.