【问题标题】:How do I construct a ConstraintViolationException in Bean Validation 1.0?如何在 Bean Validation 1.0 中构造 ConstraintViolationException?
【发布时间】:2021-02-03 07:56:55
【问题描述】:

我对 javax.validation API 感到困惑。我正在写一个简单的测试来理解它:

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);
}

我应该如何声明这组违规行为,以便可以在我的异常构造函数中使用它?

【问题讨论】:

    标签: java generics bean-validation


    【解决方案1】:

    您可以像这样解决这个问题:

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

    您可能有兴趣跟踪解决此问题的BVAL-198。

    【讨论】:

    • 从 Bean Validation 1.1 开始,构造函数已修复。
    【解决方案2】:

    这是 Bean Validation 1.0 中的一个已知可用性问题。此问题已在 Bean Validation 1.1 中通过问题 BVAL-198“简化 ConstraintViolationExceptions 的创建”得到解决。升级到 Bean Validation 1.1 或更高版本将允许您的代码按编写方式编译。

    具体问题是ConstraintViolationException 构造函数接受Set&lt;ConstraintViolation&lt;?&gt;&gt; 的constraintViolations 参数。由于Set&lt;ConstraintViolation&lt;Sample&gt;&gt; 不是Set&lt;ConstraintViolation&lt;?&gt;&gt; 的子类型,因此无法将其传递给构造函数,尝试这样做时会出现编译错误。

    Bean 验证 1.1.0 changed the constructors 改为接受 Set&lt;? extends ConstraintViolation&lt;?&gt;&gt;。由于这是Set&lt;ConstraintViolation&lt;Sample&gt;&gt; 的超类型,因此可以直接将其传递给构造函数。

    如this other answer 中所述,仍在使用 Bean Validation 1.0 时的修复是传入 Set&lt;ConstraintViolation&lt;?&gt;&gt; 而不是 Set&lt;ConstraintViolation&lt;Sample&gt;&gt;:

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

    【讨论】:

      猜你喜欢
      • 2015-06-04
      • 1970-01-01
      • 2013-06-22
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-29
      相关资源
      最近更新 更多