如何为CLI选项指定类型,例如int
或Integer
?(稍后,如何通过单个函数调用获取解析后的值?)
如何为CLI选项指定默认值?使得CommandLine.getOptionValue()
或上述函数调用返回该值,除非在命令行上指定了一个值?
如何为CLI选项指定类型,例如int
或Integer
?(稍后,如何通过单个函数调用获取解析后的值?)
如何为CLI选项指定默认值?使得CommandLine.getOptionValue()
或上述函数调用返回该值,除非在命令行上指定了一个值?
编辑:默认值现在支持了。请参阅下面答案https://dev59.com/mW035IYBdhLWcg3wKsua#14309108。
如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
可能会溢出。
我不知道是工作不正常还是最近添加的,但是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
的变量。
CLI不支持默认值。任何未设置的选项都会导致getOptionValue
返回null
。
您可以使用Option.setType方法指定选项类型,并使用CommandLine.getParsedOptionValue提取解析后的选项值作为该类型。
可以使用其他定义
getOptionValue:
public String getOptionValue(String opt, String defaultValue)
并将您的默认值包装为字符串。
示例:
String checkbox = line.getOptionValue("cb", String.valueOf(false));
输出:false
对我来说有效
int foo = getOption("foo")
,并且在出现任何问题时都默认为42。 - aibNumber.class
的问题。我天真地以为Integer.class
会起作用...! - 0xbe5077ed