@NotNull : A CharSequence, Collection, Map, or Array object is not null , but may be empty.
@NotEmpty : CharSequence, Collection, Map, or Array is not null and size> 0 .
@NotBlank : the string is not null , and the trimmed length is greater than zero .
To help you understand, let's look at how these restrictions are defined and implemented (I am using version 4.1):
The @NotNull is defined as:
@Constraint(validatedBy = {NotNullValidator.class})
This class has an isValid method defined as:
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { return object != null; }
The @NotEmpty is defined as:
@NotNull @Size(min = 1)
Thus, this restriction uses the @NotNull restriction above, and @Size , whose definition is different from the object, but must be self-learning.
Finally, the @NotBlank constraint @NotBlank defined as:
@NotNull @Constraint(validatedBy = {NotBlankValidator.class})
Thus, this restriction also uses the @NotNull restriction, but also restricts the NotBlankValidator class. This class has an isValid method defined as:
if ( charSequence == null ) { //curious return true; } return charSequence.toString().trim().length() > 0;
Interestingly, this method returns true if the string is null, but false if and only if the length of the trimmed string is 0. It is normal that it returns true if it is null, because, as I mentioned, the definition of @NotEmpty also requires @NotNull .
Here are some examples:
String name = null;
@NotNull : false
@NotEmpty : false
@NotBlank : false
String name = "";
@NotNull : true
@NotEmpty : false
@NotBlank : false
String name = "";
@NotNull : true
@NotEmpty : true
@NotBlank : false
String name = "Great answer!",
@NotNull : true
@NotEmpty : true
@NotBlank : true
Rick Hanlon II Jun 16 '13 at 20:18 2013-06-16 20:18
source share