似乎 commons-cli 目前不支持该功能,因此我将创建一个不需要参数的第二个 Options 对象,并在进行完整解析之前先对其进行解析/检查,如下所示:
public static void main(String[] args) {
// define the options with required arguments as needed
Options opts = new Options()
.addOption(Option.builder("p")
.required()
.hasArg(true)
.argName("arg")
.desc("description ")
.longOpt("param")
.build())
.addOption(Option.builder("h")
.hasArg(false)
.longOpt("help")
.desc("help description")
.build());
// first check if usage-output was requested
if (handleHelp(args, opts)) {
return;
}
// now handle the full options
CommandLineParser parser = new DefaultParser();
final CommandLine cmdLine;
try {
cmdLine = parser.parse(opts, args);
} catch (ParseException ex) {
System.out.println("Syntax error: " + ex.getMessage());
printHelp(opts);
return;
}
// now handle options and do your work
}
private boolean handleHelp(String[] args, Options opts) {
Options helpOpts = new Options()
.addOption(Option.builder("p")
//.required()
.hasArg(true)
.argName("arg")
.desc("description ")
.longOpt("param")
.build())
.addOption(Option.builder("h")
.hasArg(false)
.longOpt("help")
.desc("help description")
.build());
CommandLineParser helpParser = new DefaultParser();
final CommandLine cmdLine;
try {
cmdLine = helpParser.parse(helpOpts, args);
} catch (ParseException ex) {
System.out.println("Syntax error: " + ex.getMessage());
printHelp(opts);
return true;
}
if(cmdLine.hasOption("h")) {
printHelp(opts);
return true;
}
return false;
}
private void printHelp(Options opts) {
try (PrintWriter pw = new PrintWriter(System.out)) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(pw, 80, "myapp", "test-header", opts,
formatter.getLeftPadding(), formatter.getDescPadding(), "test-footer", true);
}
}