zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Java enum枚举配合switch使用

2023-03-07 09:44:12 时间

一看就懂,一写就忘

定义枚举

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;
        }
    }

结果