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

42

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

如何为CLI选项指定默认值?使得CommandLine.getOptionValue()或上述函数调用返回该值,除非在命令行上指定了一个值?

5个回答

51

编辑:默认值现在支持了。请参阅下面答案https://dev59.com/mW035IYBdhLWcg3wKsua#14309108

如Brent Worden所提到的,不支持默认值。

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

查看TypeHandler类和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();
}

请记住,如果提供的数字不适合于int类型,那么value可能会溢出。


9
谢谢提供的示例,这正是我所需要的。然而,我已经决定不采用CLI:它太费力了。也许只有我觉得,在处理像这样的常规情况时,它会自我否定。通过足够的设置代码,我应该能够只需说int foo = getOption("foo"),并且在出现任何问题时都默认为42。 - aib
1
是的,你说得对。我也认为库应该处理这些东西。你能推荐哪个选项解析库吗? - Patrick Spettel
我是Java世界的新手。这是我尝试过的第一个,我也不知道其他的。也许你应该把这个发帖成一个问题? - aib
1
谢谢指出Number.class的问题。我天真地以为Integer.class会起作用...! - 0xbe5077ed

31

我不知道是工作不正常还是最近添加的,但是getOptionValue()现在有一个重载版本,可以接受一个默认值(字符串类型)


1
这正是我两年前所需要的 :) - aib
@aib:很高兴能帮到你 - 那时它存在吗? - Mr_and_Mrs_D
我猜不是,否则我应该已经看到了。(或者至少有其他人在这里看到了。) - aib

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的变量。


1

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

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


我知道setType()和getParsedOptionValue()的存在,但不知道如何使用它们。你能给我一个小例子吗? - aib

0

可以使用其他定义

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

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

示例:

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

输出:false

对我来说有效


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接