枚举转换工具
package com.util;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.reflect.MethodUtils;
/**
* 功能:枚举使用工具
* 作者:Gary Huang
* 日期: 2014-3-5
* 版权:版权所有(C) 2014,QQ 834865081
*/
public class EnumUtil {
public static String getText(Class> ref , Object code){
return parseEnum(ref).get( TransformUtils.toString(code) ) ;
}
public static Map parseEnum(Class ref){
Map map = new LinkedHashMap() ;
if(ref.isEnum()){
T[] ts = ref.getEnumConstants() ;
for(T t : ts){
String text = getInvokeValue(t, "getText") ;
Enum> tempEnum = (Enum>) t ;
if(text == null){
text = tempEnum.name() ;
}
String code = getInvokeValue(t, "getCode") ;
if(code == null){
code = TransformUtils.toString( tempEnum.ordinal() ) ;
}
map.put(code , text ) ;
}
}
return map ;
}
public static T getEnumItem(Class ref , Object i){
T returnT = null ;
if(ref.isEnum()){
T[] ts = ref.getEnumConstants() ;
String tempI = Helper.checkNull(i);
for(T t : ts){
Enum> tempEnum = (Enum>) t ;
String code = getInvokeValue(t, "getCode") ;
if(code == null){
code = TransformUtils.toString( tempEnum.ordinal() ) ;
}
if(tempI.equals(code)){
returnT = t;
break ;
}
}
}
return returnT ;
}
static String getInvokeValue(T t , String methodName){
Method method = MethodUtils.getAccessibleMethod( t.getClass() , methodName);
if(null == method){
return null ;
}
try {
String text = TransformUtils.toString(method.invoke( t )) ;
return text ;
} catch (Exception e) {
return null ;
}
}
}定义枚举
public enum Yes {
A(0), B(1), C(2), D(3), F(4);
private Integer code;
Yes() {
}
Yes(int code) {
this.code = code;
}
public Integer getCode() {
return code;
}
}
枚举的应用
public static void main(String[] args) {
System.out.println( EnumUtil.getText(Yes.class, 2 ) ) ; /*获取枚举2的文本内容*/
System.out.println( EnumUtil.getEnumItem(Yes.class, 2) ) ; /*将数字2转换成为枚举*/
System.out.println( EnumUtil.parseEnum(Yes.class) ) ; /*将枚举转换成为Map*/
}