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

aib*_*aib 36 java apache-commons apache-commons-cli

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

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

小智 47

编辑:现在支持默认值.请参阅下面的答案/sf/answers/1001637591/.

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

我也有使用问题Option.setType.在调用getParsedOptionValue带有类型的选项时,我总是得到一个空指针异常Integer.class.因为文档不是真的有用,所以我查看了源代码.

纵观类型处理器类和PatternOptionBuilder类,你可以看到,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();
}
Run Code Online (Sandbox Code Playgroud)

请记住,value如果提供的数字不适合,则会溢出int.

  • 谢谢你的例子,这就是我所需要的.但是,我已经决定反对CLI:它的工作太多了.也许这只是我,但是当你必须处理像这样的常见案例时,我发现它会弄巧成拙.有了足够的设置代码,我应该只能说`int foo = getOption("foo")`并且如果出现任何问题则默认为42. (8认同)

Mr_*_*s_D 27

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