枚举Enum的一些用法

枚举的一些用法

import lombok.Getter;

/**
 * function :返回码枚举类
 * @author :mayao {yao.ma@shenmajr.com}
 * @date :2018/4/14
 */
@Getter
public enum ResponseEnum {

    //格式与构造参数保持一致
    SUCCESS(200,"成功"),
    SYSTEM_ERROR(500,"系统内部错误");

    /**
     * 枚举值不可变更,不需要set方法,直接是指final
     */
    private final int code;
    private final String message;

    /**
     * 构造函数代表本枚举的参数结构
     * @param code
     * @param message
     */
    ResponseEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 通过code获取对应枚举信息,反之亦可
     * 有时候内部数据需要转义的时候会用到
     * @param code
     * @return
     */
    public static String getMsgByCode(int code){
        for (ResponseEnum responseEnum:ResponseEnum.values()){
            if (responseEnum.getCode()==code) {
                return responseEnum.getMessage();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        //200
        System.out.println("直接获取code值:"+ResponseEnum.SUCCESS.getCode());
        //成功
        System.out.println("直接获取message值:"+ResponseEnum.SUCCESS.getMessage());
        //成功
        System.out.println("通过code获取对应message:"+ResponseEnum.getMsgByCode(200));
    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值