Search code examples
javaapache-commons-cli

Creating subcommands with commons-cli


I'm trying to create a simple argument parser using commons-cli and I can't seem to figure out how to create the following options:

java ... com.my.path.to.MyClass producer 
java ... com.my.path.to.MyClass consumer -j 8

The first argument to my program should be either producer or consumer, defining the mode which my program will run in. If it's in consumer mode, I'd like to have a -j argument which defines how many threads to service with.

Here's what I've got so far:

Options options = new Options();
options.addOption("mode", false, "Things.");

HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("startup.sh", options);

When I print out these options, the mode parameter shows up as -mode.

In Python's argparse, I'd just do the following:

parser = argparse.ArgumentParser()
parser.add_argument('mode', choices=('producer', 'consumer'), required=True)
parser.print_help()

This does exactly what I'm looking for. How can I do this in commons-cli?


Solution

  • JCommander is the answer. commons-cli doesn't seem to support these options.