@NotNull:CharSequence,Collection,Map或Array对象 不为null ,但 可以 为空。
@NotEmpty:CharSequence,Collection,Map或Array对象不为null, 并且size > 0。
@NotBlank:字符串不为null ,并且修剪后的长度大于零 。
为了帮助您理解,让我们研究一下如何定义和执行这些约束(我使用的是4.1版):
- 该
@NotNull
约束被定义为:@Constraint(validatedBy = {NotNullValidator.class})
此类的
isValid方法定义为:
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { return object != null; }- 该
@NotEmpty
约束被定义为:@NotNull
@Size(min = 1)
因此,此约束 使用
@NotNull上面的约束, 并且
@Size其定义因对象而异,但应该是自说明的。
- 最后,
@NotBlank
约束定义为:@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
: true@NotEmpty
: true@NotBlank
:false字符串名称=“好答案!”;
@NotNull
: true@NotEmpty
: true@NotBlank
: true



