我有一个用于通用类的自定义注释。看起来像这样:
@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
。
答案 0 :(得分:0)
我解决了我的问题。它与泛型类型无关。我为ConstraintValidatorContext
指定了错误的注释。将TheAnnotation
更改为MyAnnotation
后,一切都很好。