yaowanxin
6 天以前 a0914318549b357ef3c438d0c2a3714f58ea3487
src/main/java/com/ruoyi/common/enums/BaseEnum.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,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;
    }
}