Java教程:如何创建枚举来存储常量,并通过key-value、value-key的方式获取

本文介绍了如何使用Java枚举类SystemCodeConstants来替代静态finalString管理常量,提供更灵活的值映射和查询功能,以提高代码组织和团队协作效率。
摘要由CSDN通过智能技术生成

–在往常我们经常在类的上方使用static final String来代表常量,但是这种方式不利于管理,冗余杂乱,所以大多数更希望采用一些枚举类,来让同事一块使用,并且可以像Map一样随意的转换其中的值,以下就是给大家贴的模板,供大家摘抄

/**
 * 系统编码枚举
 * @author wfeil211@foxmail.com
 */
public enum SystemCodeConstants {
    BAIDU("百度","baidu"),
    TENCENT("腾讯","tencent"),
    ALI("阿里","ali"),
    HUAWEI("华为","huawei"),
    ;

    /**
     * 标题
     */
    private String label;

    /**
     * 值
     */
    private String value;

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    SystemCodeConstants(String label, String value) {
        this.label = label;
        this.value = value;
    }

    private String value() {
        return this.value;
    }

    private String label() {
        return this.label;
    }

    /**
     * 根据value获取label
     *
     * @return
     */
    public static String getLabel(String value) {
        SystemCodeConstants[] systemCodeConstants = values();
        for (SystemCodeConstants constants : systemCodeConstants) {
            if (constants.value().equals(value)) {
                return constants.label();
            }
        }
        return null;
    }

    /**
     * 根据label获取value
     *
     * @return
     */
    public static String getValue(String label) {
        SystemCodeConstants[] systemCodeConstants = values();
        for (SystemCodeConstants constants : systemCodeConstants) {
            if (constants.label().equals(label)) {
                return constants.value();
            }
        }
        return null;
    }
}

本次教程到这里就结束了,希望大家多多关注支持(首席摸鱼师 微信同号),持续跟踪最新文章吧~

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值