深入掌握Java中的enum


對於要在程序中要表示有限種類的某事物,一般我們可以采用兩種方式,一是使用:public static final String 常量;二是使用enum來表示。一般而言前者簡單,但是不能夠很好的提供更多的信息,而Java中的enum相比而言,卻十分的強大,而且更加的專業。

1. 最間C風格的enum:

/**
 * 數據源的類別:master/slave
 */
public enum DataSources {
    MASTER0, MASTER1, SLAVE0, SLAVE1, SLAVE2,  SLAVE2
}

這是最簡單的enum, 和C語言中的幾乎一樣。簡單簡潔但是功能也很弱。

2. enum 的本質

Java中的enum的本質是一個繼承java.lang.Enum的。所以他就比C風格的enum更加的強大。它可以又屬性,方法,構造函數等等,下面看一個例子:

import org.apache.commons.lang.StringUtils;
/**
 * 錯誤碼枚舉*/
public enum ErrorCodeEnum {
    /** 系統異常 */
    SYSTEM_ERROR("system_error", "系統異常"),
    /** 參數非法 */
    ILLEGAL_ARGUMENT("illegal_argument", "參數非法"),
    /** 簽名非法 */
    ILLEGAL_SIGN("illegal_sign", "簽名非法"),

// ... ...
/** 注冊碼非法 */ ILLEGAL_REG_CODE("illegal_reg_code", "注冊碼非法"); /** 枚舉碼 */ private String code; /** 枚舉描述 */ private String desc; private ErrorCodeEnum(String code, String desc) { this.code = code; this.desc = desc; } public String getCode() { return code; } public String getDesc() { return desc; } /** * 根據枚舉碼獲取枚舉 * @param code 枚舉碼 * @return 枚舉 */ public static final ErrorCodeEnum getByCode(String code) { if (StringUtils.isBlank(code)) { return null; } for (ErrorCodeEnum item : ErrorCodeEnum.values()) { if (StringUtils.equals(item.getCode(), code)) { return item; } } return null; } }

我們看到 ErrorCodeEnum  具有屬性 String codeString desc,並且具有一個私有的構造函數。原因是我們的枚舉常量需要使用這個私有的構造函數的定義:SYSTEM_ERROR("system_error", "系統異常") 就是調用的枚舉的私有構造函數:private ErrorCodeEnum(String code, String desc);所以其實ErrorCodeEnum 中定義的枚舉常量 SYSTEM_ERROR, ILLEGAL_ARGUMENT 等其實就相當於 ErrorCodeEnum 的一個實例而已,因為它們是調用ErrorCodeEnum 的私有構造函數生成的。而 ErrorCodeEnum 的屬性 String code 和 String desc,是為了更好的提供更加詳細的錯誤信息而定義的。而且在枚舉ErrorCodeEnum中還可以定義其它的各種輔助方法。

所以枚舉的本質是一個繼承與java.lang.Enum的類,枚舉常量就是枚舉的一個個的實例。枚舉可以有屬性和方法,來強化枚舉的功能。枚舉一般而言在Java中不是很好理解,一般掌握了枚舉背后的本質,那么理解起來就毫無難度了。

3. 枚舉的常用方法

 

    public static void main(String[] args){
        System.out.println(SYSTEM_ERROR.name());
        System.out.println(SYSTEM_ERROR.ordinal());
        System.out.println(SYSTEM_ERROR.toString());
        for(ErrorCodeEnum e : ErrorCodeEnum.values()){
            System.out.println(e.name());
            System.out.println(e.getDesc());
        }
        
        System.out.println(ErrorCodeEnum.SYSTEM_ERROR.name());
System.out.println(ErrorCodeEnum.valueOf(ErrorCodeEnum.class, "ILLEGAL_ARGUMENT")); }

 

String name() : Returns the name of this enum constant, exactly as declared in its enum declaration. 返回枚舉常量聲明時的字符串。

int    ordinal() : 返回枚舉常量的聲明時的順序位置,像數組的索引一樣,從0開始。

valueOf(Class<T> enumType, String name) : 其實是從 枚舉常量的字符串到 枚舉常量的轉換,相當於一個工廠方法。

name() 方法是從 枚舉常量 到 字符串的轉換,而 valueOf 是字符串到 枚舉常量的轉換

values() : 該方法是一個隱式的方法,All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type. 用於遍歷枚舉中的所有的枚舉常量。

4. enum相關的數據結構:EnumMap, EnumSet 具體可以參考jdk文檔。

5. enum 相對於 常量的優勢(略)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM