栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java enum枚举配合switch使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java enum枚举配合switch使用

一看就懂,一写就忘

定义枚举

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

结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/889099.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号