枚举注解校验字段
枚举实现校验逻辑
1:枚举注解类
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 枚举限制校验
*/
@Documented
@Constraint(validatedBy = {EnumPatternValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface EnumPattern {
/**
* 枚举类
* @return
*/
Class<? extends Enum> value();
/**
* 取值字段<br>
* 如果枚举实现了com.common.api.EnumPatternAble接口,则忽略此值,取值getPatternValue()
* 如果值为空,则取值name()
* 否则,通过反射使用getter获取fieldName的值
* @return
*/
String fieldName() default "";
/**
* 是否忽略枚举限制校验能力接口<br>
* 是否忽略枚举实现的com.perfect.perfectmall.common.api.EnumPatternAble接口,强制使用fieldName控制获取值
* @return
*/
boolean ignorePatternAble() default false;
/**
* 描述
* @return
*/
String message() default "不在取值范围内";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
2:属性类添加枚举注解
@EnumPattern(value = ChannelEnum.class,fieldName = "code",message = "不支持的支付通道")
private String channelCode;
a:fieldName:按枚举类型字段名称判断区分
b:message:字段提示错误消息
3:枚举相关类
@Getter
@AllArgsConstructor
public enum ChannelEnum {
/**
* 支付渠道
*/
ICBC("ICBC", "工商银行", (short) 1),
PSBC("PSBC", "邮政储蓄银行", (short) 2),
CCB("CCB", "建设银行", (short) 3),
UNIONPAY("UNIONPAY", "银联", (short) 4),
WEIXIN("WEIXIN", "微信", (short) 5),
ALIPAY("ALIPAY", "支付宝", (short) 6),
PAB("PAB", "平安银行", (short) 7),
BCM("BCM", "交通银行", (short) 8);
/**
* 操作代码
*/
private final String code;
/**
* 描述
*/
private final String msg;
/**
* 前端代码
*/
private final Short frontCode;
public static ChannelEnum get(String code) {
for (ChannelEnum fromEnum : values()) {
if (fromEnum.getCode().equals(code)) {
return fromEnum;
}
}
throw new CustomException(String.format("支付渠道[%s]未定义", code));
}
/**
* 通过前端代码获取操作代码
* @param frontCode
* @return
*/
public static String getCodeByFront(Short frontCode) {
for (ChannelEnum anEnum : ChannelEnum.values()) {
if (anEnum.frontCode.equals(frontCode)) {
return anEnum.code;
}
}
return null;
}
}