根據引數獲取列舉中的值
阿新 • • 發佈:2019-01-08
public class EnumGetValueUtil {
private static Logger logger = LoggerFactory.getLogger(EnumGetValueUtil.class);
/**
*
* @param clazz
* @param getTypeCodeMethodName 傳入的typeCode的get方法
* @param typeCode 傳入typeCode對應的值
* @return
*/
public static <T extends Enum<T>> T getByStringTypeCode(Class<T> clazz, String getTypeCodeMethodName,
String typeCode) {
T result = null;
try {
T[] arr = clazz.getEnumConstants();
Method targetMethod = clazz.getDeclaredMethod(getTypeCodeMethodName);
String typeCodeVal = null;
for (T entity : arr) {
typeCodeVal = targetMethod.invoke(entity).toString();
if (typeCodeVal.contentEquals(typeCode)) {
result = entity;
break;
}
}
} catch (IllegalAccessException e) {
logger.error(e.getMessage(), e);
} catch (IllegalArgumentException e) {
logger.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
logger.error(e.getMessage(), e);
} catch (NoSuchMethodException e) {
logger.error(e.getMessage(), e);
} catch (SecurityException e) {
logger.error(e.getMessage(), e);
}
return result;
}
}
private static Logger logger = LoggerFactory.getLogger(EnumGetValueUtil.class);
/**
*
* @param clazz
* @param getTypeCodeMethodName 傳入的typeCode的get方法
* @param typeCode 傳入typeCode對應的值
* @return
*/
public static <T extends Enum<T>> T getByStringTypeCode(Class<T> clazz, String getTypeCodeMethodName,
String typeCode) {
T result = null;
try {
T[] arr = clazz.getEnumConstants();
Method targetMethod = clazz.getDeclaredMethod(getTypeCodeMethodName);
String typeCodeVal = null;
for (T entity : arr) {
typeCodeVal = targetMethod.invoke(entity).toString();
if (typeCodeVal.contentEquals(typeCode)) {
result = entity;
break;
}
}
} catch (IllegalAccessException e) {
logger.error(e.getMessage(), e);
} catch (IllegalArgumentException e) {
logger.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
logger.error(e.getMessage(), e);
} catch (NoSuchMethodException e) {
logger.error(e.getMessage(), e);
} catch (SecurityException e) {
logger.error(e.getMessage(), e);
}
return result;
}
}