枚举的使用

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

  首先定义了如下的枚举类

/**
 * ${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;
    }
}

  在此考虑的如何生成新的枚举类,因为是用来做比较。而且新的枚举类的参数是通过其他类传递的。

  所以在如何生成新的枚举类时产生了困惑。先是使用了if后来改成swith,但是感觉都不太对劲,如果类的类型越来越多还是会有问题。

  通过百度使用了如下方法来生成新的枚举类

 

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

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

posted on 2018-08-27 20:33  知止而后有定  阅读(173)  评论(0)    收藏  举报

导航