【发布时间】:2011-07-31 22:25:41
【问题描述】:
如何为 CLI 选项指定类型 - 例如 int 或 Integer? (后来,如何通过单个函数调用获取解析后的值?)
如何为 CLI 选项指定默认值?这样CommandLine.getOptionValue() 或上面提到的函数调用会返回该值,除非在命令行中指定了?
【问题讨论】:
标签: java apache-commons apache-commons-cli
如何为 CLI 选项指定类型 - 例如 int 或 Integer? (后来,如何通过单个函数调用获取解析后的值?)
如何为 CLI 选项指定默认值?这样CommandLine.getOptionValue() 或上面提到的函数调用会返回该值,除非在命令行中指定了?
【问题讨论】:
标签: java apache-commons apache-commons-cli
CLI 不支持默认值。任何未设置的选项都会导致getOptionValue 返回null。
您可以使用Option.setType 方法指定选项类型,并使用CommandLine.getParsedOptionValue 将解析的选项值提取为该类型
【讨论】:
编辑:现在支持默认值。请参阅下面的答案https://stackoverflow.com/a/14309108/1082541。
正如 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 可能会溢出。
【讨论】:
int foo = getOption("foo") 并在出现任何问题时将其默认为 42。
Number.class 的事情。我天真地期望Integer.class 工作......!
我不知道是不工作还是最近添加了,但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类型的变量
【讨论】:
可以用其他的定义
getOptionValue:
public String getOptionValue(String opt, String defaultValue)
并将您的默认值包装成字符串。
例子:
String checkbox = line.getOptionValue("cb", String.valueOf(false));
输出:假
对我有用
【讨论】: