項目中,對於數據庫狀態值得管理及查詢展示不一致的處理方式之一(可以sql查詢階段做case處理,也可用本文的枚舉做法做簡單處理)。
import java.util.HashMap; import java.util.Map; public enum Enum1 { STATE1(0, "有效"), STATE2(1, "過期"), STATE3(3, "無效"); private static final Map<Integer, String> stateMap; static { //由類加載機制,靜態塊初始加載對應的枚舉屬性到map中,而不用每次取屬性時,遍歷一次所有枚舉值 stateMap = new HashMap(); for (Enum1 enum1 : values()) { stateMap.put(enum1.code, enum1.description); } } private int code; private String description; Enum1(int code, String description) { this.code=code; this.description=description; } public static String getDesByCode(Integer code) { return stateMap.get(code); } public static void main(String[] args) {
//獲取code值對應的描述,同理也可以根據描述獲取code值用於數據庫存儲。
System.out.println(getDesByCode(1));
}
}
總結:項目中關於狀態值得簡單處理方式之一,利用類加載和枚舉特性,高效查詢枚舉屬性