1,代码
public enum ResponseEnum {
SUCCEED(0, "成功"),
UNKNOWN(1001, "未知错误"),
;
private static Map<String, ResponseEnum> messageMap;
private final Integer code;
private final String description;
public static ResponseEnum messageOf(String message) {
if (messageMap == null) {
messageMap = Arrays.stream(ResponseEnum.values()).collect(Collectors.toMap(ResponseEnum::getDescription, e -> e));
}
return messageMap.getOrDefault(message, UNKNOWN);
}
ResponseEnum(Integer code, String description) {
this.code = code;
this.description = description;
}
public static ResponseEnum findByCode(Integer code){
for (ResponseEnum responseEnum : values()){
if(responseEnum.getCode().equals(code)){
return responseEnum;
}
}
return null;
}
public Integer getCode() {
return code;
}
public String getDescription() {
return description;
}
public static <T extends ResponseEnum> T getEnumByDesc(Class<T> clazz, String desc) {
for(T inner : clazz.getEnumConstants())
if(inner.getDescription().equals(desc))
return inner;
return null;
}
public static <T extends ResponseEnum> T getEnumByCode(Class<T> clazz, Integer code) {
for(T inner : clazz.getEnumConstants())
if(inner.getCode().equals(code))
return inner;
return null;
}
}
2,使用
} catch (Exception e) {
ImportTemplateDTO importDTO = cacheDto.get(dto.getRowIndex());
ResponseEnum responseEnum = ResponseEnum.getEnumByDesc(ResponseEnum.class,e.getLocalizedMessage());
importDTO.setFailReason(messageConfig.storageStr(responseEnum.name()));
ResponseEnum.getEnumByDesc(ResponseEnum.class,e.getLocalizedMessage());
errorList.add(importDTO);
iterator.remove();
log.error(e.getLocalizedMessage());
}
|