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

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

/**
 * 系统编码枚举
 * @author [email protected]
 */
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;
    }
}

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

你可能感兴趣的:(java,开发语言)