Java的公地CLI,可能值列表中的选项

问题描述:

我怎样才能让一个选项接受下面的例子只喜欢某些特定的值: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不直接的支持最简单的解决方案可能是在获取选项时检查选项的值。

+1

这仍然是真的吗? – ksl 2015-11-25 09:42:18

我以前想过这种行为,从来没有遇到过使用已经提供的方法做到这一点的方法。这并不是说它不存在。 A类跛脚方式,是添加代码自己如:

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

显然会有更好的方法来做到这一点比长的if/else,可能与enum,但应该是你”需要。另外我还没有编译这个,但我认为它应该工作。

本示例也不会使“-a”开关成为强制性的,因为在问题中未指定该开关。

另一种方式可以是扩展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(); 
     } 
    }