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源创计划”,欢迎正在阅读的你也加入,一块儿分享。