Reputation: 1510
I have plenty of classes with defined JSR 303 validation annotations on class fields. Due to the fact that we use ORM and lazy loading there is problem that constrains should be defined on getters instead of fields (ORM integration).
I do not want to spend the time modifying whole model definition. So my ideas is to move constrains at runtime. I found that constraint definitions can be obtained by BeanDescriptor like seen in example. I can get access to all my constrains defined at field level.
My problem is that there is no setter method, for change present constraints. When I debug the code, I found only two points should be changed to move constraints to getter access, but I have no clue, how to do it.
{MetaConstraint{constraintType=javax.validation.constraints.NotNull, location=BeanConstraintLocation{beanClass=ServiceAddress, propertyName='isVirtual'}}=java.lang.Object@56811df,
MetaConstraint{constraintType=org.hibernate.validator.constraints.NotEmpty, location=BeanConstraintLocation{beanClass=ServiceAddress, propertyName='postalCode'}}=java.lang.Object@56811df,
MetaConstraint{constraintType=org.hibernate.validator.constraints.NotEmpty, location=BeanConstraintLocation{beanClass=ServiceAddress, propertyName='code'}}=java.lang.Object@56811df,
...}
Thanks and hope your help.
Upvotes: 0
Views: 220
Reputation: 19109
The short answer is that you need to update your model :-)
There is not way to change the access type during runtime. The metadata API (via BeanDescriptor) you are referring to is a read only data structure. You cannot use it to change or configure the existing constraints. Even if you could make it work via some hack, it could break at any time, since you would be depending on some implementation details which might change even between minor version changes of Validator.
Also think about the further evolution of the software. Other people having to maintain or enhance the software will see the constraints being placed on the field and hence assume field access is used.
I think your best option is to move the constraints.
Upvotes: 1