How to print help using jcommander?

橙三吉。 提交于 2019-12-03 05:08:51

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

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;
 }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!