类级别的 Bean 验证不适用于泛型类



>我有一个自定义注释用于泛型类。它看起来像这样:

@MyAnnotation
public class MyGenericClass<T extends AnInterface> implements MyTemplate<T>  {
@NotNull
private Operation op;
private T value;
...
}

@MyAnnotation注释根据属性op的值验证T。这里与它关联的验证器:

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

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

最新更新