回答

4

由於公地CLI不直接的支持最簡單的解決方案可能是在獲取選項時檢查選項的值。

+1

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

6

我以前想過這種行爲,從來沒有遇到過使用已經提供的方法做到這一點的方法。這並不是說它不存在。 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」開關成爲強制性的,因爲在問題中未指定該開關。

6

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