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() { } }
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 //测试正常
以上为个人经验,希望能给大家一个参考,也希望大家多多支持呐喊教程。如有错误或未考虑完全的地方,望不吝赐教。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。