一、定义enum抽象类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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使用方法一致
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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)项的值,可设置为指定的值
一、代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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;
}
}
|
二、示例
1
2
3
4
|
//enum
StateEnum orderState=StateEnum.offline;
//orderState=StateEnum.online;
System.out.println( "state=" + orderState.getState());
|
三、打印结果
1
|
state= 20 //测试正常
|
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/jiangxuexuanshuang/article/details/87911048