1、具体实现
@Slf4j
public class EnumUtils {
/**
* 默认的翻译无效值
*/
private final static String DEFAULT_VALUE = "未知";
/**
* 枚举类获取code方法
*/
private final static String DEFAULT_METHOD_CODE = "getCode";
/**
* 枚举类获取name方法
*/
private final static String DEFAULT_METHOD_NAME = "getName";
/**
* 根据code翻译字典
* @param code 编码
* @param enumClass 枚举类反射class
* @return 翻译后的字段
*/
public static <T extends Enum<T>> T translateEnumObj(String code, Class<T> enumClass) {
// 入参校验
if (code == null || enumClass == null) {
return null;
}
try {
// 获取枚举类的所有枚举项
T[] enumConstants = enumClass.getEnumConstants();
if (enumConstants == null || enumConstants.length == 0) {
return null;
}
// 反射获取getCode和getDesc方法(注意方法名要和枚举类中的一致)
Method getCodeMethod = enumClass.getMethod(DEFAULT_METHOD_CODE);
// 遍历所有枚举项,匹配code
for (T enumItem : enumConstants) {
// 调用getCode方法获取当前枚举项的code值
String enumCode = (String) getCodeMethod.invoke(enumItem);
// 匹配成功则返回翻译描述
if (code.equals(enumCode)) {
return enumItem;
}
}
}
catch (Exception e) {
// 反射调用方法异常(如类型转换错误)
log.error("翻译枚举常量失败:{}", new JSONObject(e));
}
log.info("\n未找到其对应枚举常量,请检查:\ncode编码:{},\n枚举类类名:{}", code, enumClass.getName());
return null;
}
}
2、思路
整体思路为利用枚举类获取所有的枚举常量数组进行遍历,并通过方法反射进行获取枚举常量的code,并与输入值进行对比,最后返回枚举常量对象