package com.terra.system.helper;
|
|
import com.terra.common.helper.StringHelper;
|
import org.apache.commons.logging.Log;
|
import org.apache.commons.logging.LogFactory;
|
|
import java.lang.reflect.Method;
|
|
/**
|
* 枚举帮助类
|
* @author WWW
|
*/
|
public class EnumHelper {
|
private static final String GETTER_PREFIX = "get";
|
|
private static Log log = LogFactory.getLog(EnumHelper.class);
|
|
/**
|
* 根据名称获取枚举
|
*
|
* @param clazz 枚举类型
|
* @param name 枚举的名称,如:SqlParamType中的AND
|
* @return 返回枚举值
|
*/
|
public static <T extends Enum<T>> T nameOf(Class<T> clazz, String name) {
|
return Enum.valueOf(clazz, name);
|
}
|
|
/**
|
* 根据属性名+值获取枚举
|
*
|
* @param clazz 枚举类型
|
* @param propertyName 字段,如name,id
|
* @param value 值,如张三
|
* @return 返回枚举值
|
*/
|
public static <T extends Enum<T>> T getByString(Class<T> clazz, String propertyName, String value) {
|
String getterMethodName = GETTER_PREFIX + StringHelper.firstCharToUpperCase(propertyName);
|
T result = null;
|
try {
|
T[] arr = clazz.getEnumConstants();
|
Method targetMethod = clazz.getDeclaredMethod(getterMethodName);
|
String typeCodeVal = null;
|
for (T entity : arr) {
|
typeCodeVal = targetMethod.invoke(entity).toString();
|
if (typeCodeVal.contentEquals(value)) {
|
result = entity;
|
break;
|
}
|
}
|
} catch (Exception ex) {
|
log.error(ex.getMessage(), ex);
|
}
|
|
return result;
|
}
|
|
/**
|
* 根据整数获取枚举
|
*
|
* @param clazz 枚举类型
|
* @param propertyName 字段,如 age
|
* @param value 值,如18
|
* @return 返回枚举值
|
*/
|
public static <T extends Enum<T>> T getByInt(Class<T> clazz, String propertyName, int value) {
|
String getterMethodName = GETTER_PREFIX + StringHelper.firstCharToUpperCase(propertyName);
|
T result = null;
|
try {
|
T[] arr = clazz.getEnumConstants();
|
Method targetMethod = clazz.getDeclaredMethod(getterMethodName);
|
int typeCodeVal;
|
for (T entity : arr) {
|
typeCodeVal = Integer.parseInt(targetMethod.invoke(entity).toString());
|
if (typeCodeVal == value) {
|
result = entity;
|
break;
|
}
|
}
|
} catch (Exception ex) {
|
log.error(ex.getMessage(), ex);
|
}
|
return result;
|
}
|
}
|