は、どのように私はオプションをすることができ、次の例のように一部だけ指定された値を受け入れる:のJavaコモンズ-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
は、どのように私はオプションをすることができ、次の例のように一部だけ指定された値を受け入れる:のJavaコモンズ-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
コモンズ-CLIは、直接これをサポートしていないので、最も簡単な解決策は、オプションを取得したときにオプションの価値をチェックすることです。
私はこれまでにこのような振る舞いを望んでいましたが、すでに提供されている方法でこれを行う方法を見つけたことはありませんでした。それは存在しないと言っているわけではありません。ラメ方法の種類は、コードを追加することで、自分のような:
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);
}
}
}
明らかに、おそらくenum
と、それがあるべき/それ以外の場合は、長いよりも、これを行うためのよりよい方法があるだろう、すべてのあなた」必要があります。また、私はこれを編集していないが、私はそれが動作するはずだと思う。
この例では、質問に指定されていないため、「-a」スイッチは必須ではありません。
もう1つの方法は、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();
}
}
これは本当ですか? – ksl