Gautham Reddy Gautham Reddy - 9 months ago 54
Java Question

Apache Commons CLI : Getting list of values for an option

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?

Answer Source

You have to set maximum the number of argument values the option can take, otherwise it assumes the option only has 1 argument value

Options options = new Options();
Option option = new Option("c", "c desc");
// Set option c to take maximum of 10 arguments