0

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
2
  • I assume your question is how to parse the arguments when it is a list? Commented Nov 22, 2024 at 16:24
  • Yes! Looking to parse a list Commented Nov 22, 2024 at 17:04

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.