-help选项中的Apache Commons CLI多个参数值名称

Met*_*d89 9 java command-line arguments command-line-interface apache-commons-cli

我使用Apache Commons CLI来解析命令行参数.

我正在寻找一种在帮助中显示多个参数值名称的方法.以下是选项"startimport"的一个参数的示例:

Option startimport = OptionBuilder
                .withArgName("environment")
                .hasArg()
                .withDescription(
                        "Description")
                .create("startimport");
Run Code Online (Sandbox Code Playgroud)

当我使用-help打印出来:

-startimport <environment>                    Description
Run Code Online (Sandbox Code Playgroud)

那很好.但是,如果我想使用两个参数呢?

Option startimport = OptionBuilder
                .withArgName("firstArg secondArg")
                .hasArgs(2)
                .withDescription("Description")
                .create("startimport ");
Run Code Online (Sandbox Code Playgroud)

解析这两个参数不是问题,但我想在"-help"中输出以下内容:

startimport <firstArg> <secondArg>                    Description
Run Code Online (Sandbox Code Playgroud)

但目前我会得到:

startimport <firstArg secondArg>                    Description
Run Code Online (Sandbox Code Playgroud)

这个问题有适当的解决方案吗?

小智 25

我找到了一种以正确行事的方式解决这个问题的方法,并且认为我会分享,因为这是Google在研究过程中引导我的一个页面.此代码是使用Commons CLI 1.2编写的.

Option searchApp = OptionBuilder.withArgName("property> <value")
            .withValueSeparator(' ')
            .hasArgs(2)
            .withLongOpt("test")
            .withDescription("This is a test description.")
            .create("t");
Run Code Online (Sandbox Code Playgroud)

帮助信息如下:

-t,--test <property> <value>    This is a test description.
Run Code Online (Sandbox Code Playgroud)

它可以在命令行中使用,如下所示:

java -jar program.jar -t id 5
Run Code Online (Sandbox Code Playgroud)

并且可以在代码中检索参数的String [],如下所示:

Options options = new Options();
options.addOption(searchApp);
PosixParser parser = new PosixParser();
CommandLine cmd = parser.parse( options, args);
String[] searchArgs = cmd.getOptionValues("t");
Run Code Online (Sandbox Code Playgroud)

然后你可以用searchArgs[0]和检索值searchArgs[1].


小智 10

我用顽皮的方法来解决这个问题.

    OptionBuilder.hasArgs(3);
    OptionBuilder.withArgName("hostname> <community> <oid");
    OptionBuilder.withDescription("spans switch topology. Mutually exclusive with -s");
    Option my_a = OptionBuilder.create("a");
Run Code Online (Sandbox Code Playgroud)

它现在在帮助中正确显示.虽然我不确定这是否会产生影响.