• java 枚举enum的使用(与在switch中的使用)


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


    看看枚举类

     1 /**
     2  * 操作码类
     3  * @author kokJuis
     4  * @version 1.0
     5  * @date 2017-3-6
     6  */
     7 public enum Code {
     8  
     9     SUCCESS(10000, "操作成功"), 
    10     FAIL(10001, "操作失败"), 
    11  
    12  
    13     private int code;
    14     private String msg;
    15  
    16     //为了更好的返回代号和说明,必须呀重写构造方法
    17     private Code(int code, String msg) {
    18         this.code = code;
    19         this.msg = msg;
    20     }
    21  
    22     public int getCode() {
    23         return code;
    24     }
    25  
    26     public void setCode(int code) {
    27         this.code = code;
    28     }
    29  
    30     public String getMsg() {
    31         return msg;
    32     }
    33  
    34     public void setMsg(String msg) {
    35         this.msg = msg;
    36     }
    37  
    38     
    39     // 根据value返回枚举类型,主要在switch中使用
    40     public static Code getByValue(int value) {
    41         for (Code code : values()) {
    42             if (code.getCode() == value) {
    43                 return code;
    44             }
    45         }
    46         return null;
    47     }
    48     
    49 }

    使用:

     1 //获取代码
     2 int code=Code.SUCCESS.getCode();
     3 //获取代码对应的信息
     4 String msg=Code.SUCCESS.getMsg();
     5  
     6 //在switch中使用通常需要先获取枚举类型才判断,因为case中是常量或者int、byte、short、char,写其他代码编译是不通过的
     7  
     8 int code=Code.SUCCESS.getCode();
     9  
    10 switch (Code.getByValue(code)) {
    11  
    12     case SUCCESS:
    13         //......
    14     break;
    15  
    16     case FAIL:
    17         //......
    18     break;
    19  
    20 }
  • 相关阅读:
    【自用】【做题日记6】CTFHUB-文件上传
    【自用】【做题日记5】CTFHUB-XSS
    【自用】【做题日记4】CTFHUB-SQL注入
    【自用】【做题日记3】CTFHUB-密码口令
    【自用】【做题日记2】CTFHUB-信息泄露
    【自用】【做题日记1】CTFHUB-web前置技能
    前端-常用正则表达式
    ClashX 配置代理白名单
    http 网址 URL 特殊字符转义编码
    axios的post和request请求方法
  • 原文地址:https://www.cnblogs.com/Jeremy2001/p/10782819.html
Copyright © 2020-2023  润新知