Java 枚举(enum)
Java 枚举是一个特殊的类,一般表示一组常量,比如一年的 4 个季节,一个年的 12 个月份,一个星期的 7 天,方向有东南西北等。
Java 枚举类使用 enum 关键字来定义,各个常量使用逗号 , 来分割。
例如定义一个事件级别的枚举类。
package com.suninfo.alert.constant.incident; | |
import java.util.stream.Stream; | |
/** | |
* 事件级别枚举 | |
* | |
*/ | |
public enum AbnormalLevelEnum { | |
UNKNOWN(0, "未知"), | |
NORMAL(1, "正常"), | |
PROMPT(2, "提示"), | |
ALARM(3, "警告"), | |
SECONDARY(4, "次要"), | |
MAIN(5, "主要"), | |
SEVERITY(6, "严重"); | |
public Integer getValue() { | |
return value; | |
} | |
private Integer value; | |
private String description; | |
AbnormalLevelEnum(Integer value, String description) { | |
this.value = value; | |
this.description = description; | |
} | |
/* | |
*通过数值查询描述信息 | |
*/ | |
public static String getName(Integer value){ | |
return Stream.of(AbnormalLevelEnum.values()) | |
.filter(c -> c.value == value) | |
.findAny() | |
.orElse(null).description; | |
} | |
} |
2022-06-14 完善更方便的用法
package com.xiao.test; /** | |
* @author zhangxiao | |
* @qq 490433117 | |
* @create_date 2022/6/2 17:02 | |
*/ | |
/** | |
* @author zhangxiao | |
* @date 2022/6/2 17:02 | |
*/ | |
public class IndexTest { | |
public static void main(String[] args) { | |
String description1 = StatusEnum.FAIL.getDescription(); | |
System.out.println(description1); | |
String description = StatusEnum.getStatusType(2).getDescription(); | |
System.out.println(description); | |
StatusEnum statusType = StatusEnum.getStatusType(2); | |
switch (statusType){ | |
case BAD: | |
System.out.println("bad"); | |
break; | |
case SUCCESS: | |
System.out.println("success"); | |
break; | |
case FAIL: | |
System.out.println("fail"); | |
break; | |
default: | |
System.out.println("default "); | |
break; | |
} | |
} | |
package com.xiao.test; | |
import lombok.Getter; | |
import java.util.stream.Stream; | |
public enum StatusEnum { | |
SUCCESS(1,"成功"), | |
FAIL(2,"失败"), | |
BAD(3,"系统内部错误"); | |
private Integer value; | |
private String description; | |
StatusEnum(int value, String description) { | |
this.value = value; | |
this.description = description; | |
} | |
public static StatusEnum getStatusType(int value){ | |
return Stream.of(StatusEnum.values()).filter(s->s.getValue().equals(value)).findAny().orElse(null); | |
} | |
} |