想要使用Option
(apache.commons.cli)作为命令和子命令。
实施例
最好的方法是什么?
尝试使用简单的程序:
public static void main(String[] args) throws ParseException {
test("job", "-update"); //works fine
test("job", "-dryrun"); //works fine
test("job", "-update", "-dryrun"); // doesn't work
}
public static void test(String... args) throws ParseException {
GnuParser parser = new GnuParser();
Options options = new Options();
OptionGroup option = new OptionGroup();
option.addOption(new Option("dryrun", "dryrun"));
option.addOption(new Option("update", "update"));
options.addOptionGroup(option);
parser.parse(options, args);
}
错误:
test("job", "-update", "-dryrun");
fails with, Exception in thread "main" org.apache.commons.cli.AlreadySelectedException: The option 'dryrun' was specified but an option from this group has already been selected: 'update'
答案 0 :(得分:0)
为什么使用OptionGroup?您可以使用OptionBuilder参见Commons CLI使用方案http://commons.apache.org/proper/commons-cli/usage.html有关工作项目的完整代码,请参阅https://github.com/firefoxNX/StackOverflow/tree/master/CommonsCli
Options options = new Options();
Option dryrunOption = OptionBuilder.withArgName("dryrun")
.withDescription("dry run").create("dryrun");
options.addOption(dryrunOption);
Option updateOption = OptionBuilder.withArgName("update")
.withDescription("update").create("update");
options.addOption(updateOption);
// create the parser
GnuParser parser = new GnuParser();
// parse the command line arguments
CommandLine line = parser.parse(options, args);
Option[] opts = line.getOptions();
for(String arg: line.getArgs()){
System.out.println(arg);
}
for(Option opt: opts){
System.out.println(opt.getOpt()+" : "+opt.getValue());
}