實際開發中,很多人可能很少用枚舉類型。更多的可能使用常量的方式代替。但枚舉比起常量來說,含義更清晰,更容易理解,結構上也更加緊密。看其他人的博文都很詳細,長篇大論的,這里理論的東西不說了,一起看看在實際開發中比較常見的用法,簡單明了。
看看枚舉類
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 }
