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,代码结构更优美