10

मैं एक विकल्प निम्नलिखित उदाहरण की तरह केवल कुछ निर्दिष्ट मान स्वीकार कैसे कर सकते हैं:जावा कॉमन्स-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 

उत्तर

4

कॉमन्स-CLI कि सीधे, का समर्थन नहीं करता के बाद से सबसे आसान समाधान संभवतः एक विकल्प के मूल्य की जांच करने के लिए होता है जब आप इसे प्राप्त करते हैं।

+1

क्या यह अभी भी सच है? – ksl

6

मैं पहले इस तरह के व्यवहार चाहता था, और पहले से ही प्रदान की गई विधि के साथ ऐसा करने के लिए कभी भी ऐसा नहीं हुआ। यह कहना नहीं है कि यह अस्तित्व में नहीं है। लंगड़ा तरह से एक तरह का, कोड जोड़ने के लिए है अपने आप को जैसे:

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" स्विच अनिवार्य नहीं बनाता है, क्योंकि यह प्रश्न में निर्दिष्ट नहीं था।

6

दूसरा तरीका विकल्प वर्ग का विस्तार करना हो सकता है। काम पर हमने इसे बनाया है:

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(); 
     } 
    } 
संबंधित मुद्दे