How to print help using jcommander?

AlikElzin-kilaka picture AlikElzin-kilaka · May 5, 2015 · Viewed 10.6k times · Source

How to print help using jcommander?

I couldn't find an API for this.

Answer

SubOptimal picture SubOptimal · May 5, 2015

Find this small snippet to show the application help. Fore simplicity everthing was done in one class.

public class JCommanderExample {

    @Parameter(names = "-debug", description = "Debug mode")
    private boolean debug = false;

    @Parameter(names = "--help", help = true)
    private boolean help = false;

    public static void main(String[] args) {
        JCommanderExample jct = new JCommanderExample();
        JCommander jCommander = new JCommander(jct, args);
        jCommander.setProgramName("JCommanderExample");
        if (jct.help) {
            jCommander.usage();
            return;
        }
        System.out.println("your logic goes here");
    }
}

If you run the snippet with parameter --help the output will be

Usage: JCommanderExample [options]
  Options:
        --help

       Default: false
    -debug
       Debug mode
       Default: false