枚举的使用

  今天领导要求使用枚举类型实现一些常量设置,在此记录下使用心得(仍是一些比较简单的应用)。this

  首先定义了以下的枚举类spa

/**
 * ${DESCRIPTION}
 *
 * @author dengguoqing
 * @date 2018-08-27
 */
public enum Status {
    /**
     * 关闭状态
     */
    CLOSE("8"),
    /**
     * 将要删除状态
     */
    WILL_DELETE("9"),
    /**
     * 正常状态
     */
    OTHER("-1");

    private final String code;

    Status(String code) {
        this.code = code;
    }


    public String getCode() {
        return code;
    }
}

  在此考虑的如何生成新的枚举类,由于是用来作比较。并且新的枚举类的参数是经过其余类传递的。code

  因此在如何生成新的枚举类时产生了困惑。先是使用了if后来改为swith,可是感受都不太对劲,若是类的类型愈来愈多仍是会有问题。对象

  经过百度使用了以下方法来生成新的枚举类blog

 

package com.jrx.anytxn.account.common.constant;

/**
 * ${DESCRIPTION}
 *
 * @author dengguoqing
 * @date 2018-08-27
 */
public enum Status {
    /**
     * 关闭状态
     */
    CLOSE("8"),
    /**
     * 将要删除状态
     */
    WILL_DELETE("9"),
    /**
     * 正常状态
     */
    OTHER("-1");

    private final String code;

    Status(String code) {
        this.code = code;
    }

    public static Status getStatus(String code){
        for (Status status : Status.values()) {
            if (status.getCode().equals(code)){
                return status;
            }
        }
        return OTHER;
    }

    public String getCode() {
        return code;
    }
}

  暂时以此方法生成新的枚举对象。get

相关文章
相关标签/搜索