如何给 CLI 选项一个类型 - 例如int
or Integer
?(稍后,如何通过单个函数调用获取解析值?)
如何为 CLI 选项提供默认值?这样CommandLine.getOptionValue()
或者上面提到的函数调用会返回那个值,除非在命令行上指定了一个?
如何给 CLI 选项一个类型 - 例如int
or Integer
?(稍后,如何通过单个函数调用获取解析值?)
如何为 CLI 选项提供默认值?这样CommandLine.getOptionValue()
或者上面提到的函数调用会返回那个值,除非在命令行上指定了一个?
编辑:现在支持默认值。请参阅下面的答案https://stackoverflow.com/a/14309108/1082541。
正如 Brent Worden 已经提到的,不支持默认值。
我也有使用问题Option.setType
。getParsedOptionValue
调用带有 type 的选项时,我总是遇到空指针异常Integer.class
。因为文档并没有真正的帮助,所以我查看了源代码。
查看TypeHandler类和PatternOptionBuilder类,您可以看到必须用于or 。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();
}
请记住,value
如果提供的数字不适合int
.
我不知道是否不工作或最近添加但getOptionValue() 有一个接受默认(字符串)值的重载版本
OptionBuilder 在版本 1.3 和 1.4 中已弃用,并且Option.Builder
似乎没有设置类型的直接函数。Option
该类有一个名为 的函数setType
。您可以使用函数检索转换后的值CommandLine.getParsedOptionValue
。不知道为什么它不再是构建器的一部分。它现在需要一些这样的代码:
options = new Options();
Option minOpt = Option.builder("min").hasArg().build();
minOpt.setType(Number.class);
options.addOption(minOpt);
并阅读它:
String testInput = "-min 14";
String[] splitInput = testInput.split("\\s+");
CommandLine cmd = CLparser.parse(options, splitInput);
System.out.println(cmd.getParsedOptionValue("min"));
这将给出一个类型的变量Long
CLI 不支持默认值。任何未设置的选项都会导致getOptionValue
返回null
。
您可以使用Option.setType方法指定选项类型,并使用CommandLine.getParsedOptionValue将解析的选项值提取为该类型
可以使用其他定义
getOptionValue:
public String getOptionValue(String opt, String defaultValue)
并将您的默认值包装为字符串。
例子:
String checkbox = line.getOptionValue("cb", String.valueOf(false));
输出:假
它对我有用