Ale*_*dru 12 java command-line command-line-interface apache-commons apache-commons-cli
如何使选项仅接受某些指定值,如下例所示:
$ java -jar Mumu.jar -a foo
OK
$ java -jar Mumu.jar -a bar
OK
$ java -jar Mumu.jar -a foobar
foobar is not a valid value for -a
Run Code Online (Sandbox Code Playgroud)
另一种方法是扩展Option类.在工作中我们做到了:
public static class ChoiceOption extends Option {
private final String[] choices;
public ChoiceOption(
final String opt,
final String longOpt,
final boolean hasArg,
final String description,
final String... choices) throws IllegalArgumentException {
super(opt, longOpt, hasArg, description + ' ' + Arrays.toString(choices));
this.choices = choices;
}
public String getChoiceValue() throws RuntimeException {
final String value = super.getValue();
if (value == null) {
return value;
}
if (ArrayUtils.contains(choices, value)) {
return value;
}
throw new RuntimeException( value " + describe(this) + " should be one of " + Arrays.toString(choices));
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
} else if (o == null || getClass() != o.getClass()) {
return false;
}
return new EqualsBuilder().appendSuper(super.equals(o))
.append(choices, ((ChoiceOption) o).choices)
.isEquals();
}
@Override
public int hashCode() {
return new ashCodeBuilder().appendSuper(super.hashCode()).append(choices).toHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
我以前想要这种行为,并且从来没有遇到过用已经提供的方法做到这一点的方法.这并不是说它不存在.一种蹩脚的方式,就是自己添加代码如:
private void checkSuitableValue(CommandLine line) {
if(line.hasOption("a")) {
String value = line.getOptionValue("a");
if("foo".equals(value)) {
println("OK");
} else if("bar".equals(value)) {
println("OK");
} else {
println(value + "is not a valid value for -a");
System.exit(1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
显然,有更好的方法来做这个比长的if/else,可能有一个enum
,但这应该是你所需要的.我还没有编译这个,但我认为它应该工作.
此示例也不会强制使用"-a"开关,因为问题中未指定.