java如何将String转换为enum
生活随笔
收集整理的這篇文章主要介紹了
java如何将String转换为enum
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題
假設定義了如下的enum(枚舉):
public enum Blah {A, B, C, D }已知枚舉對應的String值,希望得到對應的枚舉值。例如,已知"A",希望得到對應的枚舉——Blah.A,應該怎么做?
Enum.valueOf()是否能實現以上目的,如果是,那我如何使用?
答案
是的,Blah.valueOf(“A”) 將會得到 Blah.A
靜態方法valueOf() 和 values() 不存在于源碼中,而是在編譯時創建,我們也可以在JavaDoc查看到它們,比如 Dialog.ModalityTyp 就中出現這兩個方法。
其他答案
當文本和枚舉值不同時,可以采用這種方式:
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); }總結
以上是生活随笔為你收集整理的java如何将String转换为enum的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PageHelper 关闭COUNT(0
- 下一篇: erlang精要(27)-异常处理