java enum枚举型使用

1、使用枚举型定义常量

我们定义常量都是: public static final… ,现在使用枚举型定义。

public enum ResultCode {
    SUCCESS(1, "请求成功"),
    DEFAULT(0,"请求失败"),;

}

2、在枚举型添加方法

public enum ResultCode {
    SUCCESS(1, "请求成功"),
    DEFAULT(0,"请求失败"),;

    private int code;
    private  String msg;
    ResultCode(int code , String msg){
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}

3、覆盖枚举型的方法

package com.zglt.customervoice.enumerate;

public enum ResultCode {
    SUCCESS(1, "请求成功"),
    DEFAULT(0,"请求失败"),;

    private int code;
    private  String msg;
    ResultCode(int code , String msg){
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return "ResultCode{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                '}';
    }
}

4、实际运用枚举类

    @RequestMapping("/unionCategory")
    @ResponseBody
    public RespEntity unionCategory(int parentId) {
        //声明返回对象
        RespEntity respEntity;
        try {
            //获取该类目下的子类目信息
            List<Category> categoryList = categoryService.getCategoryByParentId(parentId);
            respEntity = new RespEntity(ResultCode.SUCCESS);
            respEntity.setData(categoryList);
            log.info("获取类目信息成功,父类目ID:"+parentId+"\n所获得的子类目:"+categoryList);
            return respEntity;
        } catch (Exception e) {
            respEntity = new RespEntity(ResultCode.DEFAULT);
            respEntity.setMsg(RespMsg.CATEGORY_ERROR);
            log.info("获取类目信息失败,父类目ID:"+parentId);
            e.printStackTrace();
            return respEntity;
//
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值