How do I construct a ConstraintViolationException in Bean Validation 1.0?

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.


This is a known usability issue in Bean Validation 1.0. This issue was addressed in Bean Validation 1.1 by issue BVAL-198, "Simplify creation of ConstraintViolationExceptions". Upgrading to Bean Validation 1.1 or later will allow your code to compile as written.

The specific issue is that 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>>, it 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));