Search code examples
javabean-validationhibernate-validator

Purpose of @NotNull.List


When I looked among the standard constraints in Bean Validation API (JSR-303), I found the NotNull.List annotation. Its description is:

Defines several @NotNull annotations on the same element

This is valid syntax:

@NotNull.List({@NotNull, @NotNull})
private Object myObject;

But it makes no sense. Either the object is null or it is not. When would you use this annotation?

There are several other similar annotations like AssertFalse.List and AssertTrue.List.


Solution

  • You can have multiple @NotNull annotations that are mutually exclusive based on the group attribute.

    @NotNull.List({@NotNull(groups=Foo.class,message="Some message!"), 
                   @NotNull(groups=bar.class, message="Some other message!"})
    private Object myObject;
    

    I do agree it's a little silly for this example since only the payload and message can be affected, but it's probably there to remain consistent with the other annotations.

    See here for more details.