java 自定义可继承枚举Enum的案例

2025-05-29 0 74

一、定义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 //测试正常

以上为个人经验,希望能给大家一个参考,也希望大家多多支持快网idc。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/jiangxuexuanshuang/article/details/87911048

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java 自定义可继承枚举Enum的案例 https://www.kuaiidc.com/108574.html

相关文章

发表评论
暂无评论