JSR303验证组继承 [英] JSR303 Validation Group inheritance
问题描述
给出以下类和接口
class A{
@NotNull(groups=Section1.class)
private String myString
}
interface All{}
interface Section1 extends All {}
打电话时
A a = new A(); validateator.validate(a,All.class);
A a = new A(); validator.validate(a,All.class);
我希望它应该是无效的,因为myString为null,并且notNull组扩展了All,但事实并非如此.请注意,我正在使用验证器的Hibernate impl(4.0.2.GA)
I would expect that it should be invalid since myString is null and it's notNull group extends All but it does not. Note that i'm using the Hibernate impl (4.0.2.GA) of the validator
推荐答案
您的期望与规范要求相反.摘自规范(PDF上的第27页) :
Your expectations are backwards from what the specification requires. From the spec (page 27 on the PDF):
对于给定的接口Z,标记为属于组Z的约束(即,注释元素组包含接口Z的约束)或Z的任何超级接口(继承的组)都被视为组Z的一部分./p>
For a given interface Z, constraints marked as belonging to the group Z (i.e. where the annotation element groups contains the interface Z) or any of the super interfaces of Z (inherited groups) are considered part of the group Z.
换句话说,如果您用Section1.class
进行了验证,并用All.class
标记了@NotNull
,则将应用约束.但是反之亦然.
In other words, if you validated with Section1.class
and tagged @NotNull
with All.class
, the constraint would be applied. But not the other way around.
将其视为一个集合:All
是一组常见的约束,并且通过扩展All
,Section1
成为All
的超集,而不是子集.因此,当您使用All
进行验证时,它仅应用由All
及其超级接口指定的内容.
Think of it as a set: All
is a common set of constraints, and by extending All
, Section1
becomes a superset of All
, not a subset. Thus, when you validate using All
, it applies only those specified by All
and its super interfaces.
如果希望All
是Section1
中发现的约束的超集,则需要翻转继承:
If you want All
to be a superset of the constraints found in Section1
, you need to flip the inheritance:
interface All extends Section1 /*, Section2, Section3...*/ {}
从这个意义上讲,您可以对自己说All
继承 Section1
的所有约束.
In this sense, you can say to yourself that All
inherits all of the constraints of Section1
.
这也是合理的实现,因为Java使得很难找出谁扩展了某个接口(毕竟,类文件可能只有在被引用之前才可用),但是却很容易看到给定的接口扩展.
This is also the reasonable implementation, as Java makes it extremely difficult to find out who extends a certain interface (after all, the class file might not even be available until it's referenced), but trivially easy to see the interfaces that a given interface extends.
这篇关于JSR303验证组继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!