转自:http://www.cnblogs.com/cuizhf/archive/2011/08/22/2150046.html
enum<->int
enum -> int: int i = enumType.value.ordinal();
int -> enum: enumType b= enumType.values()[i];
int -> enum: enumType b= enumType.values()[i];
enum<->String
enum -> String: enumType.name()
String -> enum: enumType.valueOf(name);
--------------------------------------------------------------------------
http://stackoverflow.com/questions/604424/java-enum-converting-string-to-enum
有时间整理测试一下这个帖子中的内容,同事参考《Effective Java中文版第2版》第30条内容,更新本帖。
---------------------------------------------------------------------------
下面是Enum和字符串类型转化的例子。
第一个例子:字符串和枚举值不相同,注意覆盖toString方法。
import java.util.HashMap; import java.util.Map; 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; } // Implementing a fromString method on an enum type private static final Map<</span>String, Blah> stringToEnum = new HashMap<</span>String, Blah>(); static { // Initialize map from constant name to enum constant for(Blah blah : values()) { stringToEnum.put(blah.toString(), blah); } } // Returns Blah for string, or null if string is invalid public static Blah fromString(String symbol) { return stringToEnum.get(symbol); } @Override public String toString() { return text; } }
import java.util.HashMap; import java.util.Map; public enum Blah { A, B, C, D; // Implementing a fromString method on an enum type private static final Map<</span>String, Blah> stringToEnum = new HashMap<</span>String, Blah>(); static { // Initialize map from constant name to enum constant for(Blah blah : values()) { stringToEnum.put(blah.toString(), blah); } } // Returns Blah for string, or null if string is invalid public static Blah fromString(String symbol) { return stringToEnum.get(symbol); } }
至于整形和Enum之间的转换,也可类似处理。
来源:https://www.cnblogs.com/sunxucool/archive/2012/12/03/2800021.html