Apache Commons CLI : Getting list of values for an option
It looks like i am a bit late for the party but apache commons cli evolved and now (at least in 1.3.1) we have a new way to set that there can be unlimited number of arguments
Option c = Option.builder("c")
.hasArgs() // sets that number of arguments is unlimited
.build();
Options options = new Options();
options.addOption(c);
You have to specify two parameters setArgs
and setValueSeparator
. Then you can pass a list of arguments like -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(',');
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
option.setArgs(10);
options.addOption(option);
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);