最近為了便于對狀態碼的描述信息進行解析,學習了一下Enum的使用,發現還挺好使的。
首先,定義一個Enum的類Status,有兩個屬性statusValue狀態碼 以及 statusDesc狀態描述
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
public enum Status { STATUS_OK( "01" , "成功" ), STATUS_FAILED( "02" , "失敗" ), STATUS_NOTHING( "03" , "未知狀態" ); private Status(String statusValue, String statusDesc){ this .statusValue = statusValue; this .statusDesc = statusDesc; } //通過statusValue獲取狀態描述 public static String getStatusDesc(String statusValue){ for (Status s : Status.values()){ if (s.statusValue.equals(statusValue)){ return s.statusDesc; } } return null ; } //重寫toString方法 @Override public String toString(){ return "statusValue=" + this .statusValue + ",statusDesc=" + this .statusDesc; } private String statusValue; //狀態值 private String statusDesc; //狀態描述 public String getStatusValue() { return statusValue; } public void setStatusValue(String statusValue) { this .statusValue = statusValue; } public String getStatusDesc() { return statusDesc; } public void setStatusDesc(String statusDesc) { this .statusDesc = statusDesc; } } |
測試如下
1
2
3
4
5
6
7
8
|
public class App { public static void main( String[] args ) { System.out.println(Status.getStatusDesc( "01" )); //輸出:成功 System.out.println(Status.STATUS_FAILED.getStatusDesc()); //輸出:失敗 System.out.println(Status.STATUS_NOTHING.toString()); //輸出:statusValue=03,statusDesc=未知狀態 } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/fengxm/p/7462069.html