package com.ruoyi.common.enums;
|
|
|
import com.fasterxml.jackson.annotation.JsonCreator;
|
import com.fasterxml.jackson.annotation.JsonValue;
|
|
public interface BaseEnum {
|
@JsonValue
|
Integer getCode();
|
|
String getValue();
|
|
/**
|
* 通用静态工具方法(可被所有枚举调用)
|
*/
|
/**
|
* 通用静态工具方法:支持从 Integer 或 String 类型的 Code 进行反序列化
|
*/
|
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
|
static <E extends Enum<E> & BaseEnum> E fromCode(Class<E> enumClass, Object code) {
|
if (code == null) {
|
return null;
|
}
|
|
// 目标 Code 的整数值
|
Integer targetCode = null;
|
|
if (code instanceof Integer) {
|
// 1. 如果传入的是数字 (Integer)
|
targetCode = (Integer) code;
|
} else if (code instanceof String) {
|
// 2. 如果传入的是字符串 ("1")
|
try {
|
// 尝试将字符串转换为整数
|
targetCode = Integer.valueOf((String) code);
|
} catch (NumberFormatException e) {
|
// 如果字符串不是有效的数字(例如 "Unknown"),则 targetCode 保持为 null
|
// 您也可以在这里记录日志或执行其他错误处理
|
// System.err.println("无法将字符串 Code 转换为数字: " + code);
|
return null; // 或者在找不到匹配的情况下返回 null
|
}
|
}
|
// else if (code instanceof Long) { ... 您也可以添加对 Long 类型的支持 }
|
|
if (targetCode == null) {
|
return null;
|
}
|
|
// 使用获取到的整数值进行查找
|
for (E e : enumClass.getEnumConstants()) {
|
if (e.getCode().equals(targetCode)) {
|
return e;
|
}
|
}
|
return null;
|
}
|
|
}
|