java如何將String轉換爲enum



Java 必知必會 第 7 篇

(精挑 Stack Overflow在java中排名前100的問題java

懂得這些問題的答案幫你解決80%開發問題 )編程


問題

假設定義了以下的enum(枚舉):數組

  
    
  
  
   
   
            
   
   
  1. 微信

  2. 工具

  3. flex

public enum Blah { A, B, C, D}

已知枚舉對應的String值,但願獲得對應的枚舉值。例如,已知"A",但願獲得對應的枚舉——Blah.A,應該怎麼作?
Enum.valueOf()是否能實現以上目的,若是是,那我如何使用?this

答案

是的,Blah.valueOf("A") 將會獲得 Blah.Aspa

靜態方法valueOf() 和 values() 不存在於源碼中,而是在編譯時建立,咱們也能夠在JavaDoc查看到它們,好比 Dialog.ModalityTyp 就中出現這兩個方法。.net

其餘答案

當文本和枚舉值不一樣時,能夠採用這種方式:3d

  
    
  
  
   
   
            
   
   




public enum Blah { A("text1"), B("text2"), C("text3"), D("text4"); private String text; Blah(String text) { this.text = text; } public String getText() { return this.text; } public static Blah fromString(String text) { for (Blah b : Blah.values()) { if (b.text.equalsIgnoreCase(text)) { return b; } } return null; }}

fromString方法中,throw new IllegalArgumentException("No constant with text " + text + " found") 會比直接返回null更優秀.

其餘答案

我有一個挺讚的工具方法:

  
    
  
  
   
   
            
   
   
/** * A common method for all enums since they can't have another base class * @param <T> Enum type * @param c enum type. All enums must be all caps. * @param string case insensitive * @return corresponding enum, or null */public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) { if( c != null && string != null ) { try { return Enum.valueOf(c, string.trim().toUpperCase()); } catch(IllegalArgumentException ex) { } } return null;}

你能夠這麼使用:

  
    
  
  
   
   
            
   
   
public static MyEnum fromString(String name) { return getEnumFromString(MyEnum.class, name);}

推薦閱讀:

Google評分卡

java中如何將數組轉換爲List

去掉煩人的「!=null"

從一個多層嵌套循環中直接跳出



本文分享自微信公衆號 - 硬核編程(hardcorecode)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索