42

如何给 CLI 选项一个类型 - 例如intor Integer?(稍后,如何通过单个函数调用获取解析值?)

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

4

5 回答 5

49

编辑:现在支持默认值。请参阅下面的答案https://stackoverflow.com/a/14309108/1082541

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

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

查看TypeHandler类和PatternOptionBuilder类,您可以看到必须用于or 。Number.classintInteger

这是一个简单的例子:

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.

于 2011-05-10T20:13:44.790 回答
30

我不知道是否不工作或最近添加但getOptionValue() 一个接受默认(字符串)值的重载版本

于 2013-01-13T22:46:07.473 回答
2

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

于 2017-10-17T21:17:06.720 回答
1

CLI 不支持默认值。任何未设置的选项都会导致getOptionValue返回null

您可以使用Option.setType方法指定选项类型,并使用CommandLine.getParsedOptionValue将解析的选项值提取为该类型

于 2011-04-07T20:12:08.217 回答
0

可以使用其他定义

getOptionValue:
public String getOptionValue(String opt, String defaultValue)

并将您的默认值包装为字符串。

例子:

String checkbox = line.getOptionValue("cb", String.valueOf(false));

输出:假

它对我有用

于 2019-11-20T13:32:12.993 回答