19

How to print help using jcommander?

I couldn't find an API for this.

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277

2 Answers2

38

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
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • Note that the constructor used here `JCommander(jct, args)` is now deprecated. See Francesco Capodanno's answer below for updated syntax using the Builder pattern for object construction. – jrbe228 Jun 08 '22 at 19:45
6

With the newer version of JCommander you need to create a instantiation of JCommander.

For example the main is:

public class Usage {
  public static void main(String...argv) {
    Args args = new Args();
    JCommander jct = JCommander.newBuilder().addObject(args).build();
    jct.parse(argv);
    if (args.isHelp()) {
         jct.usage();
    }
  }
}

With a Args Class like that (if you not define your parameter in the Main):

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;

public class Args {

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

 public boolean isHelp() {
    return help;
 }
}