holmis83
holmis83

Reputation: 16604

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.

Upvotes: 8

Views: 7243

Answers (2)

iamiddy
iamiddy

Reputation: 3073

As to the @NotNull case, multiple @NotNull annotations might be needed for different validation groups as @dfb explained. But the same may be accomplished by listing those groups in the groups attribute. This is well explained here with test cases

In the bean validation API javadoc, for every constraint annotation, there's a corresponding .List annotation. For example, for @NotNull, there's @NotNull.List, for which JavaDoc says:

Defines several @NotNull annotations on the same element

What would you accomplish with multiple @NotNull annotations that you cannot accomplish with one @NotNull?

Upvotes: 0

dfb
dfb

Reputation: 13289

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.

Upvotes: 10

Related Questions