Creating subcommands with commons-cli

I am trying to create a simple argument parser using commons-cli and I cannot figure out how to create the following parameters:

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

      

The first argument to my program must be either producer

or consumer

, which specifies the mode in which my program will run. If it is in mode consumer

, I would like to have an argument -j

that specifies the number of threads to serve.

Here's what I have so far:

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

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

      

When I print these parameters, the parameter is mode

displayed as -mode

.

In Python, argparse

I would simply do the following:

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

      

This is exactly what I am looking for. How can I do this in commons-cli?

+3


source to share


2 answers


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



+2


source


What I did for things like this was to have separate parameters for each class. Basically, check the first argument to decide which list to pass to the parser. FWIW, I don't consider this a "hack" solution.



+2


source







All Articles