gpt4 book ai didi

java - 如何通过反射或任何其他方式手动触发 javax 验证?

转载 作者:行者123 更新时间:2023-12-02 11:23:49 26 4
gpt4 key购买 nike

我正在使用validation-api-2.0.1.Finalhibernate-validator-6.0.13.Final 。我想对以下情况进行验证,

我创建了一个自定义验证来验证 List<Map<String,Object>>

BookInfo.java

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
validatedBy = {BookInfoValidator.class}
)
public @interface BookInfo {
String message() default "Should not be empty";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

BookInfoValidator.java

public class BookInfoValidator implements ConstraintValidator<ValidateUserInfo, List<Map<String, Object>>> {

private final ContentRepositoryClient contentRepository;

public ValidateUserInfoValidator(ContentRepositoryClient contentRepository) {
this.contentRepository = contentRepository;
}

@Override
public void initialize(ValidateUserInfo constraintAnnotation) {

}

@Override
public boolean isValid(List<Map<String,Object>> map, ConstraintValidatorContext constraintValidatorContext) {
//In the list of Map the key will be "text,email,date etc etc" based on the key i would like to
//validate with the proper validation constraints
//ex) for Email invoke javax.validation.constraints.Email.class from validation-api
//I am not sure how to manually invoke the validation annotations.
return false;
}
}

BookInfoView.java

class BookInfoView {
@BookInfo
private List<Map<String, Object>> bookInfos;
}

在 map 列表中,键为“文本、电子邮件、日期等”。基于 key ,我想使用适当的验证约束进行验证电子邮件调用异常 javax.validation.constraints.Email.class来自验证 API。我不知道如何手动调用验证注释。

任何提示或帮助将不胜感激。

最佳答案

I am not sure how to manually invoke the validation annotations.

我正在回答上面引用的内容。 ,可以通过编程方式调用验证,如果验证失败,您将收到一组失败消息。以下是执行相同操作的步骤:

  1. 构建ValidatorFactory
  2. ValidatorFactory 获取 Validator 实例
  3. 使用 validate() 方法执行验证
  4. 处理验证结果constraintViolations.iterator().next().getMessage()

显示一些代码,下面是上述所有四个步骤的代码片段:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<BookInfoView>> constraintViolations = validator.validate(bookInfoViewObj);
assertEquals( "Should not be empty", constraintViolations.iterator().next().getMessage() );

Hibernate Validator 框架提供了各种其他功能来验证一个或多个实体,然后处理结果。最好看看official document .

关于java - 如何通过反射或任何其他方式手动触发 javax 验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52953420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com