前言
在项目中,会存在很多枚举,比如下面颜色和水果的枚举,COLOR[RED(1),GREEN(2),BLUE(3)],FRUIT[APPLE(4),BANANA(5),ORANGE(6)],但是问题是,如果要增加枚举类型,就会涉及修改代码的问题,一个比较常见的例子是,枚举生成一个列表,供前台选择,如果增加类型,那么前后台都需要进行修改。
一个思路,是将枚举项保存在数据库里,项目启动或定时刷新枚举项。在项目中,只定义枚举类型,比如
public enum COLOR{}
public enum FRUIT{}
在接口中,使用COLOR.valueOf()就可以获取枚举,并传入后面的处理层了。为什么要使用枚举呢?类型安全么,只要可以获取枚举,就说明前台传的值是正确的,即进行了范围校验。
代码
代码是参考了一篇文章https://www.niceideas.ch/roll...
有兴趣的可以看一下。他的例子,是在一个数据库表里面有一张类似业务流水表,上面有一个CODE字段,代码了对记录的不同处理,CODE很多,他不想手写大量的if...else语句,想转成enum进行处理(这个我还没有相同,动态的enum也没办法直接在代码上switch case,那么是不是他在生成的枚举上,包含了调用的方法)。
下面是在他代码之上,进行了些许的修改,便于适应我自己的业务场景。
public enum CodeInfoEnum {
LOCK(1L,1L,"LOCK_TYPE","LOCK"),UNLOCK(1L,2L,"LOCK_TYPE","LOCK");
public Long classId;
public Long infoId;
public String classCode;
public String infoCode;
CodeInfoEnum(Long classId,Long infoId,String classCode,String infoCode){
this.classId = classId;
this.infoId = infoId;
this.classCode = classCode;
this.infoCode = infoCode;
}
public static CodeInfoEnum getByInfoId(Long infoId){
return CodeInfoEnum.valueOf(infoId+"");
}
public static List<CodeInfoEnum> getByClassId(Long classId){
return Arrays.stream(CodeInfoEnum.values()).filter(item->item.classId.equals(classId)).collect(Collectors.toList());
}
public static CodeInfoEnum getByClassCodeAndInfoCode(String classCode,String infoCode){
Optional<CodeInfoEnum> opt = Arrays.stream(CodeInfoEnum.values()).filter(item->item.classCode.equals(classCode)&&item.infoCode.equals(infoCode)).findFirst();
return opt.orElse(null);
}
@Override
public String toString() {
return "CodeInfoEnum{" +
"classId=" + classId +
", infoI