java enum在switch中的使用

实际开发中,很多人可能很少用枚举类型。更多的可能使用常量的方式代替。但枚举比起常量来说,含义更清晰,更容易理解,结构上也更加紧密。看其他人的博文都很详细,长篇大论的,这里理论的东西不说了,一起看看在实际开发中比较常见的用法,简单明了。

看看枚举类


    /**
     * 操作码类
     * @author kokJuis
     * @version 1.0
     * @date 2017-3-6
     */
    public enum Code {
     
        SUCCESS(10000, "操作成功"),
        FAIL(10001, "操作失败"),
     
     
        private int code;
        private String msg;
     
        //为了更好的返回代号和说明,必须呀重写构造方法
        private Code(int code, String msg) {
            this.code = code;
            this.msg = msg;
        }
     
        public int getCode() {
            return code;
        }
     
        public void setCode(int code) {
            this.code = code;
        }
     
        public String getMsg() {
            return msg;
        }
     
        public void setMsg(String msg) {
            this.msg = msg;
        }
     
        
        // 根据value返回枚举类型,主要在switch中使用
        public static Code getByValue(int value) {
            for (Code code : values()) {
                if (code.getCode() == value) {
                    return code;
                }
            }
            return null;
        }
        
    }


使用:

    //获取代码
    int code=Code.SUCCESS.getCode();
    //获取代码对应的信息
    String msg=Code.SUCCESS.getMsg();
     
    //在switch中使用通常需要先获取枚举类型才判断,因为case中是常量或者int、byte、short、char,写其他代码编译是不通过的
     
    int code=Code.SUCCESS.getCode();
     
    switch (Code.getByValue(code)) {
     
        case SUCCESS:
            //......
        break;
     
        case FAIL:
            //......
        break;
     
    }
 

猜你喜欢

转载自blog.csdn.net/aa1215018028/article/details/85049995