Java commons-cli, options with list of possible values

Alexandru picture Alexandru · Nov 28, 2009 · Viewed 8.3k times · Source

How can I make an option accept only some specified values like in the following example:

$ 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

Answer

sly7_7 picture sly7_7 · Aug 9, 2010

The other way can be to extend the Option class. At work we have made that:

    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();
      }
  }