Tôi đã xem các tài liệu nhưng không thể xem cách lấy CLI của Apache Commons để xử lý tùy chọn "dấu gạch nối kép" mà thường chấm dứt xử lý tùy chọn.Làm thế nào để Apache CLI xử lý dấu gạch ngang kép?
Hãy xem xét các dòng lệnh sau đây trong đó có một tùy chọn "-opt" có thể mất một đối số tùy chọn mà không được chỉ định:
MyProgram -opt -- param1 param2
Tôi muốn các tùy chọn để kết thúc với không có đối số trong trường hợp này, nhưng Apache trả về "-" làm đối số. Nếu tùy chọn được phép cho nhiều hơn một đối số, thì một số hoặc tất cả các tham số sẽ được trả về dưới dạng đối số.
Đây là mẫu mã minh họa vấn đề này:
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);
}
}
Bạn đang sử dụng phiên bản mới nhất Apache Commons CLI ** 1.2 **? –
Có, tôi đang sử dụng 1,2 – MykennaC
Sau đó, 'PosixParser' bên dưới sẽ hoạt động. Xem [PosixParser.java] (http://javasourcecode.org/html/open-source/commons-cli/commons-cli-1.2/org/apache/commons/cli/PosixParser.java.html) mã nguồn: nó xử lý với '--' (xem' private void processNonOptionToken (giá trị String, boolean stopAtNonOption) 'tại dòng 182). –