JSR 349验证:静态方法的ExecutableValidator.validateParameters

时间:2017-03-04 22:58:55

标签: java validation bean-validation jsr349

BeanValidation 1.1规范定义API ExecutableValidator.validateParameters以验证对给定方法的参数施加的所有约束。

然而,API要求它传递一个对象实例,在该对象实例上调用要验证的方法:

/**
 * Validates all constraints placed on the parameters of the given method.
 *
 * @param <T> the type hosting the method to validate
 * @param object the object on which the method to validate is invoked
 * @param method the method for which the parameter constraints is validated
 * @param parameterValues the values provided by the caller for the given method's
 *        parameters
 * @param groups the group or list of groups targeted for validation (defaults to
 *        {@link Default})
 * @return a set with the constraint violations caused by this validation;
 *         will be empty if no error occurs, but never {@code null}
 * @throws IllegalArgumentException if {@code null} is passed for any of the parameters
 *         or if parameters don't match with each other
 * @throws ValidationException if a non recoverable error happens during the
 *         validation process
 */
<T> Set<ConstraintViolation<T>> validateParameters(T object,
                                                   Method method,
                                                   Object[] parameterValues,
                                                   Class<?>... groups);

我的问题是如何验证静态方法调用?例如,下面定义的Foo.bar方法的调用:

public class Foo {
   public static void bar(@NotNull String str) {...}
}

1 个答案:

答案 0 :(得分:2)

Bean Validation 1.1不支持静态方法。来自Requirements on classes to be validated

  

托管约束并期望由Bean Validation提供程序验证的对象必须满足以下要求:

     
      
  • [...]
  •   
  • 静态字段和静态方法不在验证范围内。
  •   

有些实现者可能会在将来支持它作为增强功能(例如,Hibernate Validator的HV-606),但规范本身并没有。 2.0 draft of the specification中仍然明确不支持它。