Using the Java port of the Argparse4j library, how can I pass a list as a cli argument? I know there are answers to this querstion in Python, but am looking for a Java example.
For example how can I access the --list
argument in this code as an actual Java List type.
ArgumentParser parser = ArgumentParsers.newFor("main").build();
parser.addArgument("-l", "--list")
.help("Argument list to parse");
Then run the code with
java Main --list foo bar fizz
To parse the list of arguments you are just missing a parameter when constructing your ArgumentParser
, from your code:
// note that "main" should be your class name not your main method IIRC
ArgumentParser parser = ArgumentParsers.newFor("main").build();
parser.addArgument("-l", "--list")
.nargs("*") // Here is the trick, this will accept 0 or N arguments
.help("Argument list to parse");
And same as in your Python answer link nargs
will also accept +
which means it requires at least one argument.
To parse/get the list of arguments you would need:
//I'm assuming you have a main method with args parameter here
Namespace ns = parser.parseArgs(args);
List<String> list = ns.getList("list");
System.out.println("Parsed list: " + list);
For this call java main --list arg1 arg2 arg3
it will output:
Parsed list: [arg1, arg2, arg3]