以前只知道使用没注意具体区别,特此整理总结下。
我们常说的字符串为空,其实就是一个没有字符的空数组。比如:
String a = "";
a 就可以称为是一个空字符串。由于 String 在 Java 中底层是通过 char 数组去存储字符串的,所以空字符串对应的 char 数组表现形式为
private final char value[] = new char[0];
但实际工作中,我们需要对字符串进行一些校验,比如:是否为 null,是否为空,是否去掉空格、换行符、制表符等也不为空。比较简单的就是用 Str != null && Str.length() >0 来判断。
一、框架的工具类校验
我们一般都是通过一些框架的工具类去做这些判断,比如:apache 的 commons jar 包。比如 StringUtils.isEmpty(String str) 和 StringUtils.isBlank(String str)
isEmpty和isBlank的区别在于
isEmpty仅仅是判断空和长度为0字符串。
isBlank判断的是空,长度为0,空白字符(包括空格,制表符\t,换行符\n,换页符\f,回车\r)组成的字符串。
主要区别代码验证
StringUtils.isEmpty(" “) = false
StringUitls.isBlank(” ") = true
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("aaa") = false
StringUtils.isEmpty("\t \n \r \f") = false
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUitls.isBlank(" ") = true
StringUtils.isEmpty("aaa") = false
StringUtils.isEmpty("\t \n \r \f") = true
顺便在引包的时候,会出现org.apache.commons.lang和org.apache.commons.lang3两种选择,lang3是Apache Commons 团队发布的工具包,要求jdk版本在1.5以上,相对于lang来说完全支持java5的特性,废除了一些旧的API。
所以引用lang3就好啦。
二、注解@NotNull,@NotBlank,@Valid自动判定空值
@NotNull:不能为null,但可以为empty
@NotEmpty:不能为null,而且长度必须大于0
@NotBlank:只能作用在String上,不能为null,而且调用trim()后,长度必须大于0
举例如下
public class Order {
@NotNull(message = "用户ID不能为空")
private Long userID;
@NotNull(message = "收货人地址id不能为空")
private Long addressID;
@NotBlank(message = "备注不为空")
private String comment;
}
参考文章
https://blog.youkuaiyun.com/liusa825983081/article/details/78246792
https://www.jb51.net/article/184134.html
https://blog.youkuaiyun.com/qq_39964694/article/details/81183701
http://www.360doc.com/content/18/0829/14/10072361_782131739.shtml