使用 ConstraintValidator 对两种类型进行自定义 bean 验证

Custom bean validation with tow types using ConstraintValidator

我正在学习本教程https://www.baeldung.com/spring-mvc-custom-validator

我现在面临一种情况,我有两种不同的类型,一种是 List<String>,另一种是另一种类型 class 是 Set<String>

我想使用正则表达式检查其中字符串元素的有效性。 ^[a-z0-9]+[-_]*[a-z0-9]*$

所以不用两个 bean 验证注释,一个是 List<String>

implements 
  ConstraintValidator<ContactNumberConstraint, List<String>>

另一个是Set<String>

implements 
  ConstraintValidator<ContactNumberConstraint, Set<String>>

是否可以让一个 class 接受这两种类型?如果是,代码片段将对我很有帮助

因为 ListSet 都是 Collection 并且您不关心其实现的细节(您只打算遍历元素并验证它们)你可以只需使用 implements ConstraintValidator<ContactNumberConstraint, Collection<String>>