自定义注解枚举值校验
1. 定义注解
@Constraint(validatedBy = InEnumConstraintValidator.class)
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InEnum {
/**
* 提示的message
* @return message
*/
String message() default "类型传入错误";
/**
* 用于校验的枚举
*/
Class<? extends Enum<?>> enumClass();
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
2 定义枚举接口
public interface EnumListValidService<T> {
/**
* 枚举存在
*
* @param value
* @return
*/
boolean exist(T value);
}
3.定义实现
public class InEnumConstraintValidator implements ConstraintValidator<InEnum, Object> {
private Class<? extends Enum> enumClass;
@Override
public void initialize(InEnum constraintAnnotation) {
enumClass = constraintAnnotation.enumClass();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
Enum[] enumConstants = enumClass.getEnumConstants();
if (ArrayUtil.isEmpty(enumConstants)) {
return true;
}
Enum enumConstant = enumConstants[0];
boolean isImpl = enumConstant instanceof EnumListValidService;
if(!isImpl){
ServiceException.throwException(enumClass.getSimpleName()+"未实现接口EnumListValidService");
}
EnumListValidService enumListValidService = (EnumListValidService) enumConstant;
return enumListValidService.exist(value);
}
}
4. 使用
@AllArgsConstructor
@Getter
public enum SpecsActivityTypeEnum implements EnumListValidService<Integer> {
FIRST_ORDER(1,"首单优惠"),
LIMITED_TIME(2,"限时买一赠一"),
PURCHASE_LIMIT(3,"限购");
private Integer code;
private String desc;
@Override
public boolean exist(Integer value) {
Set<Integer> sets = Arrays.stream(SpecsActivityTypeEnum.values())
.map(SpecsActivityTypeEnum::getCode)
.collect(Collectors.toSet());
return sets.contains(value);
}
}
标签:enumClass,自定义,校验,value,枚举,EnumListValidService,return,public
From: https://www.cnblogs.com/lyc88/p/18256649