java enum類自定義屬性


enum類自定義屬性

這就是enum比static靜態變量好用的地方了,可以賦予每一個枚舉值若干個屬性,例如

實例1:

public enum GasStationChannel {
    ZH("中化", "100001"),
    APP("APP", "100002"),
    QZ("撬裝", "100003"),
    ZYW("找油網", "100004"),
    YZG("油掌櫃", "100005"),
    YZX("油戰線", "100006"),
    SHELL("殼牌", "100007"),
    CHEBEI("車唄", "100008"),
    SHANGAO("山東高速", "100009"),
    GUANDE("冠德", "100010");

    private String name;
    private String code;

    GasStationChannel(String name, String code) {
        this.name = name;
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public static GasStationChannel parse(String code) {
        if(code==null){
            return null;
        }
        for (GasStationChannel channelType : GasStationChannel.values()) {
            if (channelType.getCode().equals(code)) {
                return channelType;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return "name:"+this.name+",code:"+this.code;
    }}

 實例2:

public enum Domain {


    XB("11","西北"),
    HD("13","華東"),
    DB("14","東北"),
    HB("15","華北");

    private String code;
    private String name;

    Domain(String code,String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }
    public String getName(){
        return name;
    }

    /**
     * 根據domain code,返回枚舉類型
     */
    public static Domain getDomain(String code) throws Exception {

        Domain domain = null;
        switch (code.trim()) {
            case "11":
                domain = XB;
                break;
            case "13":
                domain = HD;
                break;
            case "14":
                domain = DB;
                break;
            case "15":
                domain = HB;
                break;
            default:
                throw new Exception(String.format("傳入的域ID[%s]不存在,請檢查!", code));
        }
        return domain;
    }
}

  以上兩種都能實現,根據個人喜好選擇,個人更傾向於實例1,代碼結構更優美


免責聲明!

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



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