首先是簡要描述:
[java] view plain copy
@NotNull://CharSequence, Collection, Map 和 Array 對象不能是 null, 但能夠是空集(size = 0)。
@NotEmpty://CharSequence, Collection, Map 和 Array 對象不能是 null 而且相關對象的 size 大於 0。
@NotBlank://String 不是 null 且去除兩端空白字符後的長度(trimmed length)大於 0。
@NotNull://CharSequence, Collection, Map 和 Array 對象不能是 null, 但能夠是空集(size = 0)。
@NotEmpty://CharSequence, Collection, Map 和 Array 對象不能是 null 而且相關對象的 size 大於 0。
@NotBlank://String 不是 null 且去除兩端空白字符後的長度(trimmed length)大於 0。
爲了你們更好地理解,下面讓咱們看下這些註解都是怎麼定義的(在version 4.1中):
一、@NotNull:
定義以下:
[java] view plain copy
@Constraint(validatedBy = {NotNullValidator.class})
@Constraint(validatedBy = {NotNullValidator.class})
這個類中有一個isValid方法是這麼定義的:
[java] view plain copy
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
return object != null;
}
public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
return object != null;
}
對象不是null就行,其餘的不保證。
二、@NotEmpty:
定義以下:
[java] view plain copy
@NotNull
@Size(min = 1)
@NotNull
@Size(min = 1)
也就是說,@NotEmpty除了@NotNull以外還須要保證@Size(min=1),這也是一個註解,這裏規定最小長度等於1,也就是相似於集合非空。
三、@NotBlank:
[java] view plain copy
@NotNull
@Constraint(validatedBy = {NotBlankValidator.class})
@NotNull
@Constraint(validatedBy = {NotBlankValidator.class})
相似地,除了@NotNull以外,還有一個類的限定,這個類也有isValid方法:
[java] view plain copy
if ( charSequence == null ) { //curious
return true;
}
return charSequence.toString().trim().length() > 0;
if ( charSequence == null ) { //curious
return true;
}
return charSequence.toString().trim().length() > 0;
有意思的是,當一個string對象是null時方法返回true,可是當且僅當它的trimmed length等於零時返回false。即便當string是null時該方法返回true,可是因爲@NotBlank還包含了@NotNull,因此@NotBlank要求string不爲null。
給你們一些栗子幫助理解記憶:
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
---------------------
做者:elementf
來源:CSDN
原文:https://blog.csdn.net/elementf/article/details/72963396
版權聲明:本文爲博主原創文章,轉載請附上博文連接!java