我正在尝试在异常中存储一些通用对象的集合,并且有麻烦弄清楚泛型.具体来说,我正在使用Hibernate Validator,并希望将收集到的违规列表保存在异常中,以便在另一层应用程序中进行处理.以下是一个例子:
Set<ConstraintViolation<User>> violations = validator.validate(user); if (violations.size() > 0) { throw new ValidationException("User details are invalid",violations); }
在Eclipse中,throws行显示构造函数未定义,并建议我将构造函数签名更改为ValidationException(String,Set&ConstraintViolation< User>>>这里是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; } }
但是,我想保留ValidationException通用,以便我可以使用它不仅仅是用户验证.我试过Set< ConstraintViolation<? extends Object>>而且得到相同的结果.
有没有办法完成我想要做的事情?
解决方法
您需要将违规设置参数声明为Set<?扩展ConstraintViolation<?> ;::::
public ValidationException(String msg,Set<? extends ConstraintViolation<?>> violations) { super(msg); this.violations = Collections.unmodifiableSet( new HashSet<ConstraintViolation<?>>(violations)); }
那么一切都应该按预期工作.
这具有防御性复制所给予的Set的另外的好处,确保异常的内部集合不能被更改.