Gau*_*ddy 29 java command-line-interface apache-commons
对于CLI,我需要传入一个int数组作为特定选项的输入.
示例 - 以下命令将接受customerIds数组并执行某些操作.
myCommand -c 123 124 125
我使用Apache commons CLI实现了CLI,我使用getOptionValues("c")来检索此数组.
问题是,这只返回数组中的第一个元素,即[123],而我期望它返回[123,124,125].
我的代码的精简版本,
CommandLine cmd;
CommandLineParser parser = new BasicParser();
cmd = parser.parse(options, args);
if (cmd.hasOption("c")){
String[] customerIdArray = cmd.getOptionValues("c");
// Code to parse data into int
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮我在这里找出问题吗?
Vei*_*koW 42
我想在这里添加这个作为@Zangdak的答案,并在同样的问题上添加我的发现.
如果不调用#setArgs(int)则会发生RuntimeException.当您知道此选项的确切最大参数量时,请设置此特定值.当此值未知时,类Option具有常量:Option.UNLIMITED_VALUES
这将改变gerrytans对以下内容的回答:
Options options = new Options();
Option option = new Option("c", "c desc");
// Set option c to take 1 to oo arguments
option.setArgs(Option.UNLIMITED_VALUES);
options.addOption(option);
Run Code Online (Sandbox Code Playgroud)
ger*_*tan 35
您必须设置该选项可以采用的参数值的最大值,否则它假定该选项只有1个参数值
Options options = new Options();
Option option = new Option("c", "c desc");
// Set option c to take maximum of 10 arguments
option.setArgs(10);
options.addOption(option);
Run Code Online (Sandbox Code Playgroud)
Dav*_*ang 11
看起来我对派对来说有点晚了但是apache commons cli已经发展了,现在(至少在1.3.1中)我们有了一种新方法来设置可以有无限数量的参数
Option c = Option.builder("c")
.hasArgs() // sets that number of arguments is unlimited
.build();
Options options = new Options();
options.addOption(c);
Run Code Online (Sandbox Code Playgroud)
您必须指定两个参数setArgs和setValueSeparator。然后您可以传递一个参数列表,例如-k=key1,key2,key3.
Option option = new Option("k", "keys", true, "Description");
// Maximum of 10 arguments that can pass into option
option.setArgs(10);
// Comma as separator
option.setValueSeparator(',');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22242 次 |
| 最近记录: |