javaargumentsapache-commonsapache-commons-cli

Apache commons CLI - repeated options


I've looked around a bit, and this may be just a case of incorrect terminology but is it possible for Apache commons CLI to handle repeated options? eg:

program --arg value1 --arg value2 ...

I know that you can specify multiple option arguments so it will accept stuff like...

program --arg value1 value2

... but I'd like to handle an arbitrary number of repeated options. Does anyone know if/how this is possible?

I've found this question which is somewhat similar, but it was never answered.


Solution

  • Yes, it is possible:

    String[] args = { "-arg", "value1", "-arg", "value2" };
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    options.addOption("arg", true, "Argument");
    CommandLine line = parser.parse( options, args );
    
    String values[] = line.getOptionValues("arg");
    System.out.println(Arrays.asList(values));
    

    Result:

    [value1, value2]