2014-03-01 75 views
0

我有內部枚舉類:如何設置一定的價值通過其屬性來枚舉

public class Apartment implements Comparable<Apartment> { 
    // more properties 
    private StarRating rating; 
    private SleepPlaces sleepPlaces; 


    public enum StarRating { 
     TWO_STARS("two stars"), THREE_STARS("three stars"), FOUR_STARS("four stars"), FIVE_STARS("five stars"); 

     private String description; 

     private StarRating(String description) { 
      this.description = description; 
     } 
     public String getDescription() { 
      return description; 
     } 
    } 

    public void setRating(StarRating rating) { 
     this.rating = rating; 
    } 

正如你可以看到它有description值,描述該枚舉元素。

而我需要從jsp選擇字段設置枚舉。跳過一些jsp代碼,我們有一些字符串值,如 - two stars,已由用戶選擇。

我想將它設置爲Apartment對象,但我不能用enum的valueOf()來做到這一點。它引發IllegalArgumentException

一些例如

public class Test { 
    public static void main(String[] args) { 
     Apartment app = new Apartment(); 

     String rating2 = "TWO_STARS"; 
     app.setRating(Enum.valueOf(Apartment.StarRating.class, rating2)); 
     System.out.println("here is rating: " + app.getRating()); 

     String rating = "two stars"; 
     app.setRating(Enum.valueOf(Apartment.StarRating.class, rating)); 
     System.out.println("here is rating: " + app.getRating()); 

    } 
} 

輸出:

here is rating: TWO_STARS 
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant com.lelyak.model.Apartment.StarRating.two stars 
    at java.lang.Enum.valueOf(Enum.java:236) 
    at com.lelyak.application.Test.main(Test.java:18) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:606) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) 

如何實現第二個變體爲rating價值?有什麼建議麼?

如何通過enum的值設置枚舉元素?

SOLUTION:

添加靜態方法來枚舉:

public static StarRating getByDescription(String description){ 
     if(description != null){ 
      for(StarRating sr : StarRating.values()){ 
       if(description.equalsIgnoreCase(sr.description)){ 
        return sr; 
       } 
      } 
     } 
     return null; 
    } 

回答

1

我想你實際上問的是如何通過description設置枚舉。有沒有內置的構造,可以讓你這樣做,但你可以添加一個靜態方法到你的枚舉:

public static StarRating getByDescription(String description){ 
    if(description == null){ 
     return null; 
    } 
    for(StarRating sr : StarRating.values()){ 
     if(description.equals(sr.description)){ 
      return sr; 
     } 
    } 
    return null; 
} 
+2

我建議使用equalsIgnoreCase只是爲了確保 – Bitman

0

您不能使用方法 'Enum.valueOf' 通過描述來解決枚舉。你可以寫在「公寓」類自己的方法來解決它