简体   繁体   English

Java中注释类型的自定义验证器

[英]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 ] [Animal.DOG,Animal.CAT,Animal.COW,Animal.DOG]

I create special annotation type to valid this List: 我创建特殊的注释类型来验证此列表:

@AnimalListConstaint @AnimalListConstaint

I have also localized, parametrized message in properties file(animal_en.properties): 我还在属性文件(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" my.localized.message.for.animal.unique =“列表中的动物{0}不唯一” my.localized.message.for.animal.enemies =“动物{0}和{1}不能在列出来,因为他们是敌人”

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): 所以我写了验证方法(我的类实现了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) 布尔值= hasDuplicateAnimal(animalList)

to

Animal animal = giveMeDuplicateAnimal(animalList) 动物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. 我对Commons-Collections中的谓词逻辑有很好的经验。 Predicates are very simple logic units (implementing "public boolean evaluate(Object o)") that can easaily be reused. 谓词是非常简单的逻辑单元(实现“公共布尔评估(对象o)”),可以很容易地重用。 So you could write conditions for dublicate animals in collections and use the same rule for validation and for filtering. 因此,您可以为集合中的成对动物编写条件,并使用相同的规则进行验证和过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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