This article mainly introduces the case of java custom inheritable enumeration Enum, which has a good reference value, and I hope it will be helpful to everyone. Let's follow the editor to take a look
One, define the enum abstract class
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() {
}
}
Second, the actual inheritance of enum, consistent with the use of 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");
}
3. Enumeration can continue to be inherited for enumeration classification.
Supplement: The value of a custom enumeration (Enum) item in Java can be set to a specified value
One, the code
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;
}
}
Two, example
//enum
StateEnum orderState=StateEnum.offline;
//orderState=StateEnum.online;
System.out.println("state="+ orderState.getState());
Three, print results
state=20 //测试正常
The above is personal experience, I hope to give you a reference, and I hope you can support the editor. If there are mistakes or not fully considered, please feel free to enlighten me.