Bean Validation 2.0/Hibernate Validator 6.0
Bean Validation 2.0 (of which Hibernate Validator 6.0 is the reference implementation) allows using its validation annotations directly on generic type arguments. This is noted in the Hibernate 6.0 release documentation:
Hibernate Validator 6.0 is the Reference Implementation of the Bean Validation 2.0 specification so it comes with all its new features:
- First class support of container element constraints and cascaded validation (think
private Map<@Valid @NotNull OrderCategory, List<@Valid @NotNull Order>> orderByCategories;
);
If the project is using Java 8 with Bean Validation 2.0, this feature can be used to validate each element of the list:
private List<@NotNull String> myString; // Validate that none of the list items is null
Bean Validation 1.2/Hibernate Validator 5.2
Hibernate 5.2 (with Bean Validation 1.2) added a limited version of the feature to allow validation annotations directly on generic type arguments. However, none of its built-in Bean Validation or Hibernate Validation constraints could be used in this manner, as the annotations do not specify ElementType.TYPE_USE
for backwards-compatibility reasons. Additionally, type argument constraints could be specified for map values but not map keys. This is all described in the Hibernate Validator 5.2 documentation:
Starting from Java 8, it is possible to specify constraints directly on the type argument of a parameterized type. However, this requires that ElementType.TYPE_USE
is specified via @Target
in the constraint definition. To maintain backwards compatibility, built-in Bean Validation as well as Hibernate Validator specific constraints do not yet specify ElementType.TYPE_USE
.
[...]
When applying constraints on an Iterable type argument, Hibernate Validator will validate each element.
[...]
Type argument constraints are also validated for map values. Constraints on the key are ignored.
Summary
In summary, if the code is using Java 8 with Bean Validation 2.0 (such as Hibernate Validator 6), the generic list & map type arguments can be annotated:
private List<@NotNull String> myString;
If the code is using Java 8 with Bean Validation 1.2 and Hibernate Validator 5.2, custom validation annotations can be written with TYPE_USE
in its definition, and applied to the generic type of the collection or map value:
private List<@MyCustomNotNull String> myString;
If the code is not using Java 8 or is on a version of Hibernate Validator prior to 5.2, a custom constraint could be written which verifies every element of a collection or map and applied to the collection or map itself.
@MyCustomNotNullElements
private List<String> myString;