@NotNull
:CharSequence,Collection,Map或Array对象 ,但 可以 为空。@NotEmpty
:CharSequence,Collection,Map或Array对象不为null, 。@NotBlank
:字符串不为null 。
为了帮助您理解,让我们研究一下如何定义和执行这些约束(我使用的是4.1版):
@Constraint(validatedBy = {NotNullValidator.class})
此类的isValid
方法定义为:
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
return object != null;
}
@NotNull
@Size(min = 1)
因此,此约束 使用@NotNull
上面的约束, @Size
其定义因对象而异,但应该是自说明的。
@NotNull
@Constraint(validatedBy = {NotBlankValidator.class})
因此,此约束还使用了@NotNull
约束,但也约束了NotBlankValidator类。此类的isValid
方法定义为:
if ( charSequence == null ) { //curIoUs
return true;
}
return charSequence.toString().trim().length() > 0;
有趣的是,如果字符串为null,则此方法返回true,但仅当修剪后的字符串的长度为0时,此方法才返回false。如果为null,则返回true是可以的,因为正如我提到的,@NotEmpty
定义也需要@NotNull
。
这里有一些例子:
字符串名称= null; @NotNull
:错误@NotEmpty
:错误@NotBlank
:错误
字符串名称=“”; @NotNull
: @NotEmpty
:假@NotBlank
:假
字符串名称=“”; @NotNull
: @NotEmpty
: @NotBlank
:false
字符串名称=“好答案!”;@NotNull
: @NotEmpty
: @NotBlank
: