简体   繁体   中英

custom validator for annotation type in java

I have enum:

public enum Animal {
    DOG,
    CAT,
    BIRD,
    HORSE,
    COW;

}

and List, where i have this animals:

[ Animal.DOG,Animal.CAT, Animal.COW, Animal.DOG ]

I create special annotation type to valid this List:

@AnimalListConstaint

I have also localized, parametrized message in properties file(animal_en.properties):

my.localized.message.for.animal.unique = "Animal {0} in list is not unique" my.localized.message.for.animal.enemies= "Animal {0} and {1} can't be in the list, because they are enemies"

And my validator should check this two condition:

  • Is my list unique ?
  • Is on my list enemies animals(for example cat and dog)

So i write validation method(my class implements ConstraintValidator):

 public boolean isValid(final List<Animal> animalList, final ConstraintValidatorContext context) {
        context.disableDefaultConstraintViolation();
        boolean result = true;

        if (hasDuplicateAnimal(animalList)) {
            context.buildConstraintViolationWithTemplate("{my.localized.message.for.animal.unique}")
                    .addConstraintViolation();
            result = false;
        }

        if (hasEnemiesInList(animalList)) {
            context.buildConstraintViolationWithTemplate("{my.localized.message.for.animal.enemies}")
                    .addConstraintViolation();
            result = false;
        }

        return result;
    }

and this validator throwed me localized message, but now i would like to add parameters:

change method:

boolean value = hasDuplicateAnimal(animalList)

to

Animal animal = giveMeDuplicateAnimal(animalList)

and if i have duplicate animal, then i put this animal in my message. My question is how to parametrized this message? Or maybe i should choose diffrent strategy ?

I made good experience with the Predicate Logic, found in commons-collections. Predicates are very simple logic units (implementing "public boolean evaluate(Object o)") that can easaily be reused. So you could write conditions for dublicate animals in collections and use the same rule for validation and for filtering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM