yaowanxin
5 天以前 a0914318549b357ef3c438d0c2a3714f58ea3487
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.ruoyi.common.enums;
 
 
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
 
public interface BaseEnum<T> {
    @JsonValue
    T 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;
    }
 
}