该注解用来约束字段的值必须是 false,支持 boolean 和 Boolean 类型。如果字段的值为 null,也视为有效。源码如下:
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented @Constraint(validatedBy = { }) public @interface AssertFalse { String message() default "{javax.validation.constraints.AssertFalse.message}"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; // 在同一元素上定义多个 @AssertFalse 注解。 @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented @interface List { AssertFalse[] value(); } }
注意:message、groups、payload 属性用法参考 @NotNull 注解。
示例:
package com.hxstrive.validation; import lombok.Builder; import lombok.Data; import org.hibernate.validator.HibernateValidator; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.constraints.AssertFalse; import java.util.Set; /** * 验证注解元素是否为 false * @author hxstrive.com */ @Data @Builder public class AssertFalseDemo { @AssertFalse(message = "flag 必须为 false") private boolean flag; public static void main(String[] args) { AssertFalseDemo.builder().flag(true).build().validator("case1"); // Fail AssertFalseDemo.builder().flag(false).build().validator("case2"); // OK } private void validator(String caseName) { validator(caseName, this); } private <T> void validator(String caseName, T obj) { // 手动调用 API 对定义了注解的字段进行校验 Validator validator = Validation.byProvider(HibernateValidator.class).configure() .failFast(true).buildValidatorFactory().getValidator(); Set<ConstraintViolation<T>> set = validator.validate(obj); if (set.size() > 0) { // 校验失败 System.out.println(caseName + " :: Fail :: " + set.iterator().next().getMessage()); } else { // 校验通过 System.out.println(caseName + " :: Succeed"); } } }
运行示例,输出如下:
case1 :: Fail :: flag 必须为 false case2 :: Succeed