How to change annotation / hibernate validation rules at runtime?

If you have a Java class with some fields that I want to check with the Hibernate Validator. Now I want my users to be able to configure at runtime which checks are performed.

For example:

public class MyPojo {
    ...

    @NotEmpty
    String void getMyField() {
        ... 
    }

    ...
}

Say I want to remove a check NotEmptyor replace it with Emailor CreditCardNumber, how can I do this? Is it possible? I guess this boils down to changing annotations at runtime ...

+3
source share
3 answers

You cannot do this normally.

, , Hibernate Validator.

  • ClassValidator.
  • getInvalidVaues(Object myObj). super.getInvalidValues(myObj), .
  • getInvalidValues . , (, ) .

:

public class MyObjectValidator extends ClassValidator<MyObject>
{
    public MyObjectValidator()
    {
         super(MyObject.class);
    }

    public InvalidValue[] getInvalidValues(MyObject myObj)
    {
        List<InvalidValue> invalids = new ArrayList<InvalidValue>();
        invalids.addAll(Arrays.asList(super.getInvalidValues(myObj)));

        // add custom validations here
        invalids.addAll(validateDynamicStuff(myObj));

        InvalidValue[] results = new InvalidValue[invalids.size()];
        return invalids.toArray(results);
    }

    private List<InvalidValue> validateDynamicStuff(MyObject myObj)
    {
        // ... whatever validations you want ...
    }

}

, " , , " .. , , , , , , "" .

+2

hibernate validator 4.1. .

+1

I don’t think you can remove or modify the annotation, this is part of the class definition. You can create a new class, which is possible at runtime, but a little involved. Hibernate can support programmatic access to checks and allow annotation cancellation, I don't know the API, which is good. Hibernate does a bit of building the runtime class itself ... this may be a good place to learn how to do it if you are interested.

0
source

Source: https://habr.com/ru/post/1706442/