标签:java 使用 os io strong for ar 2014
枚举转换工具
package com.util;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.reflect.MethodUtils;
/**
* <strong>功能:</strong>枚举使用工具
* <strong>作者:</strong>Gary Huang
* <strong>日期:</strong> 2014-3-5
* <strong>版权:<strong>版权所有(C) 2014,QQ 834865081
*/
public class EnumUtil {
public static String getText(Class<?> ref , Object code){
return parseEnum(ref).get( TransformUtils.toString(code) ) ;
}
public static <T> Map<String, String> parseEnum(Class<T> ref){
Map<String, String> map = new LinkedHashMap<String, String>() ;
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> T getEnumItem(Class<T> 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 <T> 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*/
}
JAVA----枚举的相互转换,布布扣,bubuko.com
标签:java 使用 os io strong for ar 2014
原文地址:http://blog.csdn.net/hfmbook/article/details/38559115