2

想要使用Option( apache.commons.cli ) 作为命令和子命令。

前任。

  1. 我的程序作业-dryrun
  2. 我的程序作业-更新
  3. 我的程序作业 -update -dryrun

最好的方法是什么?

尝试使用简单的程序:

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'
4

1 回答 1

0

你为什么使用选项组?您可以使用 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());
            }
于 2014-06-12T19:12:57.090 回答