通过枚举属性获得枚举实例

有的公司喜欢在实体中使用枚举,但是落库落整型值,理由主要就是
1、整形比字符串省地方
2、如果是字符串,设置多长
像这样

enum Gender {
    MALE(0),
    FEMALE(1);

    private int code;

    public int getCode() {
        return code;
    }

    private Gender(int code) {
        this.code = code;
    }
}

我的看法是这样,
为了节省一点硬盘而在代码中反复进行int和enum的转换完全是得不偿失
而且枚举字面值可以保证唯一性,增加code以后增加了人为失误的可能性。
在使用orm框架的时候,很多程序员可能不会、不知道、不想去做自定义类型的处理器,因此造成int和enum的处理到处都是,并且特别恶心
另外,如果是枚举,我们直接使用==即可,使用int就有可能造成 int==Integer 的情况。

但是有的公司已经这么用了,可能暂时无法说服其他人,本身又不是很重要的问题,所以会妥协。

方式一 static map

enum Gender {
    MALE(0),
    FEMALE(1);

    private int                               code;

    private static final Map<Integer, Gender> MAP = new HashMap<>();

    static {
        for (Gender item : Gender.values()) {
            MAP.put(item.code, item);
        }
    }

    public static Gender getByCode(String code) {
        return MAP.get(code);
    }

    public int getCode() {
        return code;
    }

    private Gender(int code) {
        this.code = code;
    }
}

方式二 反射

public class EnumUtil {

    public static <E> E getByCode(Class<E> clz, int code) {
        try {
            for (E e : clz.getEnumConstants()) {
                Field field = clz.getDeclaredField("code");
                field.setAccessible(true);
                if (Objects.equals(field.get(e), code)) {
                    return e;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("根据code获取枚举实例异常" + clz + " code:" + code, e);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(EnumUtil.getByCode(Gender.class, 0));
    }
}

如果担心性能,可以考虑加个map

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值