For a CLI, I have a requirement to pass in an array of ints as input for a particular option.
Example - The below command would take in an array of customerIds and perform some operations.
myCommand -c 123 124 125
I have implemented the CLI using Apache commons CLI, and I am using getOptionValues("c") to retrieve this array.
The problem is that, this is returning only the first element in the array, i.e. [123], while I am expecting it to return [123, 124, 125].
A condensed version of my code,
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
}
Can someone help me identify the issue here?
I'd like to add this here as an answer to @Zangdak and to add my findings on the same problem.
If you do not call #setArgs(int)
then a RuntimeException will occur. When you know the exact maximum amount of arguments to this option, then set this specific value. When this value is not known, the class Option has a constant for it: Option.UNLIMITED_VALUES
This would change gerrytans answer to the following:
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);