[英]How do I construct a ConstraintViolationException in Bean Validation 1.0?
I am puzzled by the javax.validation API.我对 javax.validation API 感到困惑。 I am writing a simple test to understand it:我正在编写一个简单的测试来理解它:
Sample sample = new Sample();
Set<ConstraintViolation<Sample>> violations = validator.validate(sample);
if (!violations.isEmpty()) {
// Eclipse refuses to let me use my violations variable
throw new ConstraintViolationException(violations);
}
How should I declare the set of violations so I can use it in my exception constructor?我应该如何声明一组违规,以便我可以在我的异常构造函数中使用它?
This is a known usability issue in Bean Validation 1.0.这是 Bean Validation 1.0 中的一个已知可用性问题。 This issue was addressed in Bean Validation 1.1 by issue BVAL-198 , "Simplify creation of ConstraintViolationExceptions".此问题已在Bean Validation 1.1 中的BVAL-198问题“简化 ConstraintViolationExceptions 的创建”中得到解决。 Upgrading to Bean Validation 1.1 or later will allow your code to compile as written.升级到 Bean Validation 1.1 或更高版本将允许您的代码按照编写的方式进行编译。
The specific issue is that the ConstraintViolationException
constructors accepted Set<ConstraintViolation<?>>
for their constraintViolations
parameter.具体问题是ConstraintViolationException
构造函数接受Set<ConstraintViolation<?>>
作为它们的constraintViolations
参数。 Since Set<ConstraintViolation<Sample>>
is not a subtype of Set<ConstraintViolation<?>>
, it could not be passed into the constructor, with a compilation error occurring when attempting to do so.由于Set<ConstraintViolation<Sample>>
不是Set<ConstraintViolation<?>>
的子类型,因此无法将其传递到构造函数中,尝试这样做时会发生编译错误。
Bean validation 1.1.0 changed the constructors to instead accept Set<? extends ConstraintViolation<?>>
Bean 验证 1.1.0 将构造函数更改为接受Set<? extends ConstraintViolation<?>>
Set<? extends ConstraintViolation<?>>
. Set<? extends ConstraintViolation<?>>
。 As this is a supertype of Set<ConstraintViolation<Sample>>
, it can be passed directly to the constructor.由于这是Set<ConstraintViolation<Sample>>
的超类型,它可以直接传递给构造函数。
As mentioned in this other answer , the fix while still on Bean Validation 1.0 was to pass in a Set<ConstraintViolation<?>>
instead of Set<ConstraintViolation<Sample>>
:正如在另一个答案中提到的,仍然在 Bean Validation 1.0 上的修复是传入Set<ConstraintViolation<?>>
而不是Set<ConstraintViolation<Sample>>
:
throw new ConstraintViolationException(
new HashSet<ConstraintViolation<?>>(violations));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.