Myk*_*naC 5 java command-line-interface apache-commons apache-commons-cli
我查看了文档,但看不到如何让Apache Commons CLI处理通常终止选项处理的双连字符"选项".
请考虑以下命令行,该命令行具有"-opt"选项,该选项可以采用未指定的可选参数:
MyProgram -opt -- param1 param2
Run Code Online (Sandbox Code Playgroud)
我希望选项在这种情况下最终没有参数,但Apache返回" - "作为参数.如果该选项允许多个参数,那么部分或全部参数将作为参数返回.
以下是说明问题的示例代码:
package com.lifetouch.commons.cli;
import java.util.Arrays;
import org.apache.commons.cli.*;
public class DoubleHyphen {
private static Options options = new Options();
public static void main(String args[]) {
// One required option with an optional argument:
@SuppressWarnings("static-access")
OptionBuilder builder = OptionBuilder.isRequired(true).
withDescription("one optional arg").
withArgName("optArg").hasOptionalArgs(1);
options.addOption(builder.create("opt"));
// Illustrate the issue:
doCliTest(new String[] { "-opt"} );
doCliTest(new String[] { "-opt", "optArg", "param"} );
doCliTest(new String[] { "-opt", "--", "param"} );
// What I want is for the double-dash to terminate option processing.
// Note that if "opt" used hasOptionalArgs(2) then "param" would be a second
// argument to that option (rather than an application parameter).
}
private static void doCliTest(String[] args) {
System.out.println("\nTEST CASE -- command line items: " + Arrays.toString(args));
// Parse the command line:
CommandLine cmdline = null;
try {
CommandLineParser parser = new GnuParser();
cmdline = parser.parse(options, args); // using stopAtNonOption does not help
} catch (ParseException ex) {
System.err.println("Command line parse error: " + ex);
return;
}
// Observe the results for the option and argument:
String optArgs[] = cmdline.getOptionValues("opt");
if (null == optArgs) {
System.out.println("No args specified for opt");
} else {
System.out.println(optArgs.length + " arg(s) for -opt option: " +
Arrays.toString(optArgs));
}
// Observe the results for the command-line parameters:
String tmp = Arrays.toString(cmdline.getArgList().toArray());
System.out.println(cmdline.getArgList().size() +
" command-line parameter(s): " + tmp);
}
}
Run Code Online (Sandbox Code Playgroud)
为了将特殊标记--
作为选项终止符处理,您必须使用POSIX解析器.
使用
CommandLineParser parser = new PosixParser();
Run Code Online (Sandbox Code Playgroud)
代替
CommandLineParser parser = new GnuParser();
Run Code Online (Sandbox Code Playgroud)