您的位置:首页 > 其它

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

2017-12-28 16:01 621 查看
有的公司喜欢在实体中使用枚举,但是落库落整型值,理由主要就是

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  enum
相关文章推荐