一看就懂,一写就忘

Java enum枚举配合switch使用_Test

定义枚举

public enum TypeEnum {
//
type1(1, "水果"),
type2(2, "蔬菜"),
type3(3, "零食");;

private final Integer code;
private final String value;

TypeEnum(Integer code, String value) {
this.code = code;
this.value = value;
}

public Integer getCode() {
return code;
}

public String getValue() {
return value;
}

// 根据code返回枚举类型,主要在switch中使用
public static TypeEnum getByCode(Integer code) {
for (TypeEnum optionTypeEnum : values()) {
if (optionTypeEnum.getCode().equals(code)) {
return optionTypeEnum;
}
}
return null;
}
}

test

@Test
public void test(){
System.out.println(TypeEnum.getByCode(1).getValue());

System.out.println(TypeEnum.type1.getCode() + "_" + TypeEnum.type1.getValue());
System.out.println(TypeEnum.type2.getCode()+ "_" + TypeEnum.type2.getValue());
System.out.println(TypeEnum.type3.getCode()+ "_" + TypeEnum.type3.getValue());

switch (TypeEnum.getByCode(1)){
case type1:
System.out.println("吃水果");break;
case type2:
System.out.println("吃蔬菜"); break;
case type3:
System.out.println("吃零食");break;
}
}

结果

Java enum枚举配合switch使用_枚举类型_02