Raylite3
Raylite3

Reputation: 847

How do I construct a ConstraintViolationException in Bean Validation 1.0?

I am puzzled by the 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?

Upvotes: 22

Views: 25722

Answers (2)

M. Justin
M. Justin

Reputation: 21123

Starting with Bean Validation 1.1, your code will compile as written.

Sample sample = new Sample();
Set<ConstraintViolation<Sample>> violations = validator.validate(sample);
if (!violations.isEmpty()) {
    throw new ConstraintViolationException(violations);
}

You have encountered a known usability issue with Bean Validation 1.0. This issue was addressed in Bean Validation 1.1 by issue BVAL-198, "Simplify creation of ConstraintViolationExceptions".

The specific issue is that in Bean Validation 1.0, the ConstraintViolationException constructors accepted Set<ConstraintViolation<?>> for their constraintViolations parameter. 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.

Bean validation 1.1.0 changed the constructors to instead accept Set<? extends ConstraintViolation<?>>. As this is a supertype of Set<ConstraintViolation<Sample>>, a value of that type can be passed directly to the constructor.

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>>:

throw new ConstraintViolationException(
    new HashSet<ConstraintViolation<?>>(violations));

Upvotes: 1

Gunnar
Gunnar

Reputation: 18990

You can work around this like so:

throw new ConstraintViolationException(
    new HashSet<ConstraintViolation<?>>(violations));

You may be interested in tracking BVAL-198 which addresses this issue.

Upvotes: 18

Related Questions