JCommander可以帮我们解析Java的命令行工具,主要利用@Parameter配置自己所需要的参数;
在一般应用场景,我们可能只需要设置@Parameter以下几个属性值:
* names 设置命令行参数,如-old
* required 设置此参数是否必须
* description 设置参数的描述
* order 设置帮助文档的顺序
* help 设置此参数是否为展示帮助文档或者辅助功能
public class CommandArgs {
@Parameter(names = {"-s","--savepoint"},
help = true,
required = false,
description = "scheduler savepoint,default path /data/checkpoint")
private String savePoint = null;
public String getSavePoint() {
return savePoint;
}
}
public class CommandLineUtils {
public static CommandLineArgs parseSchedulerArgs(String[] args) {
CommandArgs commandArgs = new CommandArgs();
JCommander.newBuilder()
.addObject(commandArgs)
.build()
.parse(args);
return new CommandLineArgs(commandArgs.getSavePoint());
}
}
启动jar程序时:
nohup java -cp test.jar JCommandTest $1,$2 > a.log