Java – use generics in parameters of exceptions
I'm trying to store a collection of generic objects in exceptions and have trouble figuring out generics Specifically, I am using hibernate validator and want to save the collected violation list in the exception for processing in another layer of application Here is an example:
Set<ConstraintViolation<User>> violations = validator.validate(user); if (violations.size() > 0) { throw new ValidationException("User details are invalid",violations); }
In eclipse, the throws line shows that the constructor is undefined and suggests that I change the constructor signature to validationexception (string, set & constraintviolation < user > > > here is validationexception:
public class ValidationException extends Exception { private Set<ConstraintViolation<?>> violations; public ValidationException() { } public ValidationException(String msg) { super(msg); } public ValidationException(String msg,Throwable cause) { super(msg,cause); } public ValidationException(String msg,Set<ConstraintViolation<?>> violations) { super(msg); this.violations = violations; } public Set<ConstraintViolation<?>> getViolations() { return violations; } }
However, I want to keep the validationexception generic so that I can use it more than just user authentication I tried set < < constraintviolation > and get the same result
Is there any way to accomplish what I want to do?
Solution
You need to declare the violation setting parameter as set
public ValidationException(String msg,Set<? extends ConstraintViolation<?>> violations) { super(msg); this.violations = Collections.unmodifiableSet( new HashSet<ConstraintViolation<?>>(violations)); }
Then everything should work as expected
This has the additional benefit of defensive replication, ensuring that the inner set of exceptions cannot be changed