类级别的Bean验证不适用于通用类

时间:2018-08-20 15:40:11

标签: java bean-validation nested-generics

我有一个用于通用类的自定义注释。看起来像这样:

@MyAnnotation
public class MyGenericClass<T extends AnInterface> implements MyTemplate<T>  {

  @NotNull
  private Operation op;

  private T value;

  ...
}

@MyAnnotation批注根据属性T的值验证op。与此相关的验证器:

public class MyAnnotationValidator implements ConstraintValidator<TheAnnotation, MyGenericClass<? extends AnInterface>> {

@Override
public void initialize(TheAnnotation constraintAnnotation) {}

@Override
public boolean isValid(MyGenericClass<? extends AnInterface> operation, ConstraintValidatorContext context) {

    if(operation == null) return true;

    AnInterface value = operation.getValue();

    if(value == null && "add".equals(operation.getOp().name())) return false;
    if(value == null && "replace".equals(operation.getOp().name())) return false;
    if(value == null) return true;

    if("add".equals(operation.getOp().name())) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<AnInterface>> violations = validator.validate(value);

        return violations.isEmpty();
    }

    return true;
  }
}

在运行时,我有classCastException "exception":"java.lang.ClassCastException","message":"com.sun.proxy.$Proxy226 cannot be cast to ...MyAnnotation

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。它与泛型类型无关。我为ConstraintValidatorContext指定了错误的注释。将TheAnnotation更改为MyAnnotation后,一切都很好。