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 }

 

posted @ 2019-04-28 11:06  jeremy1888  阅读(14302)  评论(2编辑  收藏  举报