一、介绍
二、用法举例:
public enum DateTypeEnums {
DAY(0,'天'),
MONTH(1,"月"),
WEEK(2,"周");
public final int code;
public final String message;
DateTypeEnums(int code, String message ) {
this.code = code;
this.message = message;
}
public int getCode() {
return this.code;
}
public String getMessage() {
return message;
}
}
三、枚举在switch中的写法:
错误写法:
ResultStructureEnum type = ResultStructureEnum.valueOf(userType);
switch (type) {
case ResultStructureEnum.STUDENT:
...
break;
case ResultStructureEnum.TEACHER:
...
break;
case ResultStructureEnum.PARENT:
...
break;
...
}
# 这样编译不会通过,提示case后必须是一个常量
正确写法:
ResultStructureEnum type = ResultStructureEnum.valueOf(userType);
switch (type) {
case STUDENT:
...
break;
case TEACHER:
...
break;
case PARENT:
...
break;
...
}
# 即在 case 后面可以直接写枚举类型,不用加枚举类的类名。
如果需要根据类型的编码返回枚举实例,可以在枚举类中加入方法:
/**
* 根据编号获取对应枚举实例
*
* @param statNo
* @return
*/
public static DateTypeEnums getEnum(intcode) {
for (DateTypeEnums result : DateTypeEnums.values()) {
if (result.getCode == code) {
return result;
}
}
return null;
}
四、enum&&Function
如enum加Function校验数据
package org.demo.annotation.enums;
import org.demo.annotation.constant.MenuValueCheckFunctions;
import java.util.function.Function;
public enum MenuEnums {
USER_MANAGE("user_manage",1, MenuValueCheckFunctions.CHECK(10)),
MAIN_MANAGE("main",0, MenuValueCheckFunctions.CHECK_NO_NULL);
private final String code;
private final Integer order;
private final Function<String, String> checkFunction;
MenuEnums(String code, Integer order, Function<String, String> checkFunction) {
this.code = code;
this.order = order;
this.checkFunction = checkFunction;
}
public static String checkValue(MenuEnums menuEnums,String value) {
if(menuEnums.checkFunction != null){
return menuEnums.checkFunction.apply(value);
}
return value;
}
}
package org.demo.annotation.constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.util.function.Function;
@Slf4j
public class MenuValueCheckFunctions {
public static Function<String, String> CHECK(int maxLenth) {
return value-> {
if(value != null && value.length() > maxLenth){
//throw new BaseException("length is too lang");
log.error(value+" length is too lang");
return value.substring(0, maxLenth);
}
return value;
};
}
public static Function<String, String> CHECK_NO_NULL = value-> {
if(StringUtils.isEmpty(value)){
//throw new BaseException("value is null");
log.error("value is null");
}
return value;
};
}
测试:
public static void main(String[] args) {
List<MenuDTO> menuDTOS = new ArrayList<>();
MenuDTO userMenuDTO = MenuDTO.builder()
.url(MenuEnums.checkValue(MenuEnums.USER_MANAGE,"/myDemo/test/main"))
.build();
menuDTOS.add(userMenuDTO);
MenuDTO mainMenu = MenuDTO.builder()
.url(MenuEnums.checkValue(MenuEnums.MAIN_MANAGE,""))
.build();
menuDTOS.add(mainMenu);
}
控制台输出: