Java | 枚举Enum中使用反射转换属性值

common wx:CodingTechWork,一起学习进步。

需求

  在开发过程中,有时候需要需要根据各个枚举类中一个字段属性值转为另一个字段属性值,如根据code转为name的需求进行前端展示。本文总结一下如何通过反射简单巧妙的进行枚举属性值的互相映射。

实践

枚举类

package com.test.selfcoding;

/**
 * @Description TODO
 * @Author LiaoJy
 * @Date 2023/6/18
 */
public enum ColourEnum {
    
    

    /**
     * 红色
     */
    RED(1, "红色"),
    /**
     * 黄色
     */
    YELLOW(2, "黄色"),
    /**
     * 绿色
     */
    GREEN(3, "绿色");

    private Integer code;
    private String desc;

    ColourEnum(Integer code, String desc) {
    
    
        this.code = code;
        this.desc = desc;
    }

    public Integer getCode() {
    
    
        return code;
    }

    public String getDesc() {
    
    
        return desc;
    }

    public static String getDesc(Integer code) {
    
    
        for (ColourEnum c : ColourEnum.values()) {
    
    
            if (c.code.intValue() == code.intValue()) {
    
    
                return c.getDesc();
            }
        }
        return null;
    }

    public static Integer getCode(String desc) {
    
    
        for (ColourEnum c : ColourEnum.values()) {
    
    
            if (c.desc.equals(desc)) {
    
    
                return c.getCode();
            }
        }
        return null;
    }

    public static ColourEnum getEnum(Integer code) {
    
    
        if (code == null) {
    
    
            return null;
        }
        for (ColourEnum c : ColourEnum.values()) {
    
    
            if (c.code.intValue() == code.intValue()) {
    
    
                return c;
            }
        }
        return null;
    }

}

反射测试类


package com.test.selfcoding.service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Description
 * @Author LiaoJy
 * @Date 2023/6/18
 */
public class EnumReflectServiceTest {
    
    

    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    
    
        String codeValue = "1";
        String descValue = "黄色";
        Class<Enum> clazz = (Class<Enum>) Class.forName("com.test.selfcoding.ColourEnum");
        if (Integer.class.equals(clazz.getDeclaredField("code").getType())) {
    
    
            Method method = clazz.getMethod("getDesc", Integer.class);
            String result = (String)  method.invoke(clazz, Integer.parseInt(codeValue));
            System.out.println("颜色描述:" + result);
        }

        if (String.class.equals(clazz.getDeclaredField("desc").getType())) {
    
    
            Method method = clazz.getMethod("getCode", String.class);
            Integer result = (Integer)  method.invoke(clazz, descValue);
            System.out.println("颜色编码:" + result);
        }
    }

}

运行结果

颜色描述:红色
颜色编码:2

猜你喜欢

转载自blog.csdn.net/Andya_net/article/details/131415381
今日推荐