cevap

4

commons-cli doğrudan, yani desteklemediği En basit çözüm muhtemelen bir seçeneğin değerini aldığınızda kontrol etmektir.

+1

Bu hala geçerli mi? – ksl

6

Bu türden bir davranışı daha önce istedim ve daha önce sağlanmış bir yöntemle bunu yapmak için hiçbir yolla karşılaşmadım. Bu varolmayan demek değil. topal bir şekilde bir tür kod eklemektir kendiniz gibi:

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

Açıkçası, muhtemelen bir enum ile, ama bu olmalı/else if uzun daha bunu yapmak için daha güzel yollar var olacağını tüm' d ihtiyacım var. Ayrıca bunu derlemedim, ama işe yarayacağını düşünüyorum.

Bu örnekte, "-a" anahtarının zorunlu hale getirilmemesi de zorunludur, çünkü bu soruda belirtilmemiş.

6

Diğer yol, Seçenek sınıfını genişletmek olabilir. İşte biz bunu yaptık:

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