public static <T extends Enum<T>> T getByIntegerTypeCode(Class<T> clazz, String getTypeCodeMethodName, String typeCode) {
T result = null;
try {
//Enum接口中没有values()方法,我们仍然可以通过Class对象取得所有的enum实例
T[] arr = clazz.getEnumConstants();
//获取定义的方法
Method targetMethod = clazz.getDeclaredMethod(getTypeCodeMethodName);
String typeCodeVal;
//遍历枚举定义
for (T entity : arr) {
//获取传过来方法的
typeCodeVal = targetMethod.invoke(entity).toString();
//执行的方法的值等于参数传过来要判断的值
if (typeCodeVal.equals(typeCode)) {
//返回这个枚举
result = entity;
break;
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result;
}
上述方法累赘,可以直接用这个,也是工作之后才会的
public static String getNameByCode(String code) {
if (StringUtils.isEmpty(code)) {
return null;
}
for (ProductTypeEnum value : values()) {
if (value.getCode().equals(code)) {
return value.getName();
}
}
return code;
}
使用:
ProductTypeEnum getCode = getByIntegerTypeCode(ProductTypeEnum.class, "getCode", formula.getProductType());
String productType = getCode.getName();