开发者

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 开发者_Python百科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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜