gpt4 book ai didi

java - Apache Commons CLI - 选项类型和默认值

转载 作者:IT老高 更新时间:2023-10-28 20:51:13 35 4
gpt4 key购买 nike

如何为 CLI 选项指定类型 - 例如 intInteger? (后来,如何通过单个函数调用获取解析后的值?)

如何为 CLI 选项指定默认值?这样 CommandLine.getOptionValue() 或上面提到的函数调用会返回该值,除非在命令行中指定一个值?

最佳答案

编辑:现在支持默认值。查看答案 https://stackoverflow.com/a/14309108/1082541下面。

正如 Brent Worden 已经提到的,不支持默认值。

我也有使用 Option.setType 的问题。在类型为 Integer.class 的选项上调用 getParsedOptionValue 时,我总是遇到空指针异常。因为文档没有真正的帮助,所以我查看了源代码。

TypeHandler类和 PatternOptionBuilder class 你可以看到 Number.class 必须用于 intInteger

这是一个简单的例子:

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 可能会溢出。

关于java - Apache Commons CLI - 选项类型和默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5585634/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com