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");
}