我有自定义注释,如下所示:
@Documented
@Constraint(validatedBy = MyValidator.class)
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String message() default "message";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
}
和验证器以验证内容:
public class MyValidator implements ConstraintValidator {
@Override
public void initialize(MyAnnotation myAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
ConstraintValidatorContextImpl con = (ConstraintValidatorContextImpl)context;
String diff = getDiff(value, cleanForHTMLContext(value));
if(diff.isEmpty()){
return true;
}
return false;
}
private cleanForHTMLContext(String value) {
// Some stuff to clean up value
}
private String getDiff(String value, String cleanedValue) {
// Some stuff to compare values
}
}
我的目标是在注释属性中添加“ diff”,然后可以通过键和ResourceBundle中的属性来解析消息.
例如:当使用类型无效日期时,应该会看到以下消息:
数据无效,因为包含以下文本:{diff}.其中diff是两个字符串之间的运行时比较结果,将在isValid()方法中对其进行评估.
我试图从这样的映射参数中求值:
ConstraintValidatorContextImpl con = (ConstraintValidatorContextImpl)context;
con.getConstraintDescriptor().getAttributes().put("diff", value);
但是不幸的是,我对在ConstraintDescriptorImpl中创建的不可修改地图有例外
是否有其他可能性添加将通过错误代码解决的自定义属性?