Java 枚举是一个特殊的类,一般表示一组常量,比如一年的 4 个季节,一个年的 12 个月份,一个星期的 7 天,方向有东南西北等。
Java 枚举类使用 enum 关键字来定义,各个常量使用逗号 , 来分割。
看实现:
public void test() { | |
// 1.获取改枚举值和描述 | |
Integer type1 = LoginTypeEnum.EMAILLOGIN.getType(); | |
System.out.println(type1); | |
String description1 = LoginTypeEnum.EMAILLOGIN.getDescription(); | |
System.out.println(description1); | |
// 2.获取描述 | |
String description = LoginTypeEnum.getDescription(1); | |
System.out.println(description); | |
// 3.获取枚举类 | |
LoginTypeEnum type = LoginTypeEnum.getType(1); | |
switch (type) { | |
case SCANLOGIN: | |
System.out.println("扫描"); | |
break; | |
case EMAILLOGIN: | |
System.out.println("邮件"); | |
break; | |
case MESSAGELOGIN: | |
System.out.println("短信"); | |
break; | |
default: | |
System.out.println("无"); | |
} | |
} | |
package com.foodie.enumeration; | |
import lombok.Getter; | |
import java.util.stream.Stream; | |
public enum LoginTypeEnum { | |
EMAILLOGIN(1, "邮件登陆"), | |
MESSAGELOGIN(2, "短信登陆"), | |
SCANLOGIN(3, "扫描登陆"); | |
Integer type; | |
String description; | |
LoginTypeEnum(Integer value, String description) { | |
this.type = value; | |
this.description = description; | |
} | |
/** | |
* 通过类型获取枚举类 | |
* | |
* @param type | |
*/ | |
public static LoginTypeEnum getType(Integer type) { | |
return Stream.of(LoginTypeEnum.values()).filter(s -> s.type.equals(type)).findAny().orElse(null); | |
} | |
/** | |
* 通过类型获取描述值 | |
* | |
* @param type | |
* @return | |
*/ | |
public static String getDescription(Integer type) { | |
LoginTypeEnum[] values = LoginTypeEnum.values(); | |
return Stream.of(values).filter(s -> s.type == type).map(s -> s.description).findAny().orElse(null); | |
}} |