@Parameter(names = {"clone"}, description = "克隆远程仓库数据", arity = 1)private String cloneUrl;帮助信息
使用 usage()参数可以打印命令帮助信息。
GitCommandOptions gitCommandOptions = new GitCommandOptions();JCommander commander = JCommander.newBuilder() .addObject(gitCommandOptions) .build();commander.parse(args);// 打印帮助信息commander.usage();
运行输出帮助信息:
$ java -jar git-app.jarUsage:[options] Options: clone 克隆远程仓库数据 help, -help, -h 查看帮助信息 version, -version, -v 显示当前版本号 Default: false
虽然正确的输出了帮助信息,但是其中有 main class这段,是因为我们没有指定项目名称,我们指定项目名称为 git-app。
JCommander commander = JCommander.newBuilder() .programName("git-app") .addObject(gitCommandOptions) .build();参数排序
在帮助信息中,如果想要自定义参数顺序,可以通过 order = 来排序,数字越小越靠前。
@Parameter(names = {"version", "-version", "-v"}, description = "显示当前版本号", order = 2)private boolean version = false;参数绑定完整测试
package com.wdbyte.jcommander.v2;import com.beust.jcommander.Parameter;/** * @author https://www.wdbyte.com */public class GitCommandOptions { @Parameter(names = {"help", "-help", "-h"}, description = "查看帮助信息", order = 1, help = true) private boolean help; @Parameter(names = {"clone"}, description = "克隆远程仓库数据", order = 3, arity = 1) private String cloneUrl; @Parameter(names = {"version", "-version", "-v"}, description = "显示当前版本号", order = 2) private boolean version = false; //...get method}
GitApp.java
package com.wdbyte.jcommander.v2;import com.beust.jcommander.JCommander;public class GitApp { public static void main(String[] args) { GitCommandOptions gitCommandOptions = new GitCommandOptions(); JCommander commander = JCommander.newBuilder() .programName("git-app") .addObject(gitCommandOptions) .build(); commander.parse(args); // 打印帮助信息 if (gitCommandOptions.isHelp()) { commander.usage(); return; } if (gitCommandOptions.isVersion()) { System.out.println("git version 2.24.3 (Apple Git-128)"); return; } if (gitCommandOptions.getCloneUrl() != null) { System.out.println("clone " + gitCommandOptions.getCloneUrl()); } }}
Copyright 2015-2022 财务报告网版权所有 备案号: 京ICP备12018864号-19 联系邮箱:29 13 23 6 @qq.com