Apache Commons CLI:获取选项的值列表
对于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 }
有人可以帮我在这里找出问题吗?
您必须设置该选项可以采用的最大参数值的数量,否则它假定该选项只有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);
我想在这里添加这个作为@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);
看起来我对派对来说有点晚了,但是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);
- 如何使用apache通用配置加载多个配置文件(java)
- 使用Linux上的Apache Commons Compression压缩文件时编码错误
- 反序列化会话数据时出现InvalidClassException错误
- apache-commons-config PropertiesConfiguration:丢失最后一个属性后的注释
- FTPSClient返回MalformedServerReplyException:无法解析响应代码
- 我何时应该使用Apache Commons的Validate.isTrue,何时应该使用’assert’关键字?
- Google Guava vs. Apache Commons
- 用Java确定另一个国家的互联网时间
- Java BeanUtilsBean:将Date转换为String