package com.se.system.utils;
|
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
|
import java.lang.reflect.Method;
|
|
@SuppressWarnings("ALL")
|
public class EnumUtils {
|
private static final String GETTER_PREFIX = "get";
|
|
private static final Logger log = LoggerFactory.getLogger(EnumUtils.class);
|
|
public static <T extends Enum<T>> T nameOf(Class<T> clazz, String name) {
|
return Enum.valueOf(clazz, name);
|
}
|
|
public static <T extends Enum<T>> T getByString(Class<T> clazz, String propertyName, String value) {
|
String getterMethodName = GETTER_PREFIX + StringUtils.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;
|
}
|
|
public static <T extends Enum<T>> T getByInt(Class<T> clazz, String propertyName, int value) {
|
String getterMethodName = GETTER_PREFIX + StringUtils.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;
|
}
|
}
|