Gunnar向我提出了一个关于Bean Validation的有趣问题。为了不让知识保密,我认为更广泛地分享会更有用。
是否可以使用约束元数据API确定给定的约束是在字段级别还是属性级别指定的?
首先,在许多情况下,你不需要进行区分。如果Java从一开始就支持属性,我们就不会有这个问题(叹息)。
无论如何,答案是肯定的。你可以微调从元数据API返回的内容。
PropertyDescriptor property =
validator.getConstraintsForClass(Address.class)
.getConstraintsForProperty("street1");
Set<ConstraintDescriptor<?>> fieldConstraints =
property
.findConstraints()
.lookingAt(Scope.LOCAL_ELEMENT)
.declaredOn(ElementType.FIELD)
.getConstraintDescriptors();
Set<ConstraintDescriptor<?>> propertyConstraints =
property
.findConstraints()
.lookingAt(Scope.LOCAL_ELEMENT)
.declaredOn(ElementType.METHOD)
.getConstraintDescriptors();
关键在于使用findConstraints()流畅API。你有三种方法来限制检索的元数据
- declaredOn(ElementType... types): 定义在哪里查找约束(方法、字段等)
- lookingAt(Scope scope): 定义是否在超类/接口上查找约束(默认)或否
- unorderedAndMatchingGroups(Class<?>... groups): 限制匹配给定集合组的约束(注意组序列的顺序不被尊重)
就是这样。