如何为命令行界面选项指定类型-如int
或Integer
?(稍后,如何通过单个函数调用获得解析后的值?)
如何为CLI选项提供默认值?以便CommandLine.getOptionValue()
或上面提到的函数调用返回该值,除非在命令行中指定了该值?
发布于 2011-05-11 04:13:45
编辑:现在支持默认值。请参阅下面的answer 。
正如Brent Worden已经提到的,不支持默认值。
我在使用Option.setType
时也遇到了一些问题。在类型为Integer.class
的选项上调用getParsedOptionValue
时,我总是得到一个空指针异常。因为文档并没有真正的帮助,所以我查看了源代码。
查看TypeHandler类和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();
}
请记住,如果提供的数字不适合int
,则value
可能会溢出。
https://stackoverflow.com/questions/5585634
复制相似问题