Variable field in a constraint annotation

早过忘川 提交于 2019-11-30 05:14:59

The easiest thing to do is take one step back: the constraint/validator you have written works on a field-level, but what you want to enforce is a cross-field dependency i.e. a class-level constraint.

Rewrite your constraint and validator to work at the class level (i.e. the annotation will go on the class, not on the field). That way you'll get access to the entire class. In your isValid(..) method, simply do a get on both the fields, compare, and return appropriately.

As the compiler said annotations must be constant (i.e. you can determine the value at compile time.) Now If I'm guessing correctly it looks like you are using this annotation to denote that the values of those fields should be equal when run through the equals field validator. One approach you could take is using reflection. Instead of trying to annotate with the value, annotate with the field name instead

public class MyBean{

     private String field1;

     @EqualsField("field1")
     private String field2;
}

Then in your validator you can read the name of the field and use reflection to access it

Object o = object.getClass().getDeclaredField(annotationValue).get(object);
o == object.(field with annotation) OR
o.equals(object.(field with annotation));

Depending on what you are trying to do you may need to add in logic based on the field type, but still the same general principle.

larsrc

Check out this previous question, has multiple solutions for cross-field validation: Cross field validation with Hibernate Validator (JSR 303)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!