Apache Commons CLI 可选和位置参数

Apache Commons CLI Optional and positional argument

事情是这样的:我想要一个标志“-pre”,如果没有填充,将创建一个时间戳前缀;如果已填充,则使用指定的前缀。

Option prefixOption = OptionBuilder.create(O_PREFIX);
prefixOption.setLongOpt(O_PREFIX_LONG);
prefixOption.setArgName("prefix");
prefixOption.setDescription("Put a prefix (default is timestamp) to output directory.");
prefixOption.setType(String.class);
prefixOption.setOptionalArg(true);

后来..

System.out.println(commandLine.hasOption(O_PREFIX));
System.out.println(commandLine.getOptionValue(O_PREFIX));

执行次数:

\> mon_execution -pre
true
null


\> mon_execution -pre Hahaha
true
null

如果我强制使用 arg pre

prefixOption.setArgs(1); (in first snipet)

命令行将下一个参数作为-pre的参数并中断解析。

有什么想法吗?

选项声明的变化

Option prefixOption = new Option("pre", "prefix", true, "Put a prefix (default is timestamp) to output directory.");
prefixOption.setOptionalArg(true);

并且,最重要的是,遵守顺序并 位置可选参数放在列表的末尾

下面的问题,值得深思:如何使用多个位置可选选项?另一个 post - 另一天的另一个问题。

谢谢。