大家好,又见面了,我是你们的朋友全栈君。
开发过程中为了代码的可阅读性和可维护性,很多类型字段往往会习惯使用枚举去定义,可是在一些判断里面想用switch去代替if else 就会出现以下问题
public enum SexType {
MAN(1, "男"),
GIRL(2, "女"),
;
private int type;
private String work;
SexType(int type, String work) {
this.type = type;
this.work = work;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getWork() {
return work;
}
public void setWork(String work) {
this.work = work;
}
}
如果直接使用会因为case后跟的是常量表达式而导致报错
1、修改枚举类,新增一个静态方法,getByType()
package com.jaryn.emun;
public enum SexType {
MAN(1, "男"),
GIRL(2, "女"),
OTHER(0, "未知"),
;
private int type;
private String work;
SexType(int type, String work) {
this.type = type;
this.work = work;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getWork() {
return work;
}
public void setWork(String work) {
this.work = work;
}
public static SexType getByType(int type){
for (SexType constants : values()) {
if (constants.getType() == type) {
return constants;
}
}
return OTHER;
}
}
2、修改方法逻辑
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/159286.html原文链接:https://javaforall.cn