一、定义enum抽象类 public class AbstractEnum { private static final MapString, AbstractEnum nameEnumMap = new ConcurrentHashMap(); @Getter protected String name; protected AbstractEnum () { } protected AbstractEnum(String name) { thi
一、定义enum抽象类
public class AbstractEnum { private static final Map<String, AbstractEnum> nameEnumMap = new ConcurrentHashMap<>(); @Getter protected String name; protected AbstractEnum () { } protected AbstractEnum(String name) { this.name = name; if (!nameEnumMap.containsKey(name)) { nameEnumMap.put(name, this); } } public boolean equals(AbstractEnum abstractEnum) { return this.name == null || abstractEnum == null ? false : this.name.equals(abstractEnum.getName()); } public String toString() { return this.name; } public static AbstractEnum valueOf(String name) { if (name == null) throw new NullPointerException("Name is null"); AbstractEnum result = nameEnumMap.get(name); if (result != null) { return result; } throw new IllegalArgumentException( "No enum constant exists, name is." + name); } public static void init() { } }
二、实际继承enum,与enum使用方法一致
public class TypeEnum extends AbstractEnum { private static final Map<String, TypeEnum> nameEnumMap = new ConcurrentHashMap<>(); protected TypeEnum(String name) { super(name); if (!nameEnumMap.containsKey(name)) { nameEnumMap.put(name, this); } } public static TypeEnum valueOf(String name) { if (name == null) throw new NullPointerException("Name is null"); TypeEnum result = nameEnumMap.get(name); if (result != null) { return result; } throw new IllegalArgumentException( "No enum constant exists, name is." + name); } public static final TypeEnum TYPE_ONE = new TypeEnum("TYPE_ONE"); }
三、可继续继承枚举,进行枚举分类。
补充:Java中自定义枚举(Enum)项的值,可设置为指定的值
一、代码
package base.lang; /** * ClassName: StateEnum * @Description: TODO * @author fuming * @date 2016年11月27日 */ public enum StateEnum { //添加枚举的指定常量 online(10), offline(20); //必须增加一个构造函数,变量,得到该变量的值 private int mState=0; private StateEnum(int value) { mState=value; } /** * @return 枚举变量实际返回值 */ public int getState() { return mState; } }
二、示例
//enum StateEnum orderState=StateEnum.offline; //orderState=StateEnum.online; System.out.println("state="+ orderState.getState());
三、打印结果
state=20 //测试正常
以上为个人经验,希望能给大家一个参考,也希望大家多多支持易盾网络。如有错误或未考虑完全的地方,望不吝赐教。