JSR303 Validation Group inheritance

倾然丶 夕夏残阳落幕 提交于 2019-12-07 16:51:50

问题


Given the following classes and interfaces

class A{
  @NotNull(groups=Section1.class)
  private String myString
}

interface All{}
interface Section1 extends All {}

When calling

A a = new A(); validator.validate(a,All.class);

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


回答1:


Your expectations are backwards from what the specification requires. From the spec (page 27 on the PDF):

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.

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.

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.

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...*/ {}

In this sense, you can say to yourself that All inherits all of the constraints of Section1.

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.



来源:https://stackoverflow.com/questions/9775088/jsr303-validation-group-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!