首页 > > > 是否注意过isEmpty 和 isBlank 区别?
阅读本文大概需要 1 分钟。
org.apache.commons.lang.StringUtils 类提供了 String 的常用操作,最为常用的判空有如下两种 isEmpty(String str) 和 isBlank(String str)。
我们通过源码来分析区别:
public static boolean isEmpty(String str) {
return str == null || str.length() == ;
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
public static boolean isBlank(String str) {
int strLen;
if (str != null && (strLen = str.length()) != ) {
for(int i = ; i < strLen; ++i) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
1.StringUtils.isEmpty(String str)判断某字符串是否为空,为空的标准是 str==null 或 str.length()==0
2.StringUtils.isBlank(String str)判断某字符串是否为空或长度为 0 或由空白符 (whitespace) 构成
3.StringUtils.isNotEmpty(String str)等价于!isEmpty(String str)
4.StringUtils.isNotBlan(String str)等价于!isBlank(String str)
StringUtils.isBlank(String str) 来执行判空操作,判断的条件更多更具体,特别是进行参数校验时,推荐使用。
另外,你们项目是否有isEmpty和isBlank混用的情况?

往期精彩回顾

朕已阅 
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69902700/viewspace-3170063/ ,如需转载,请注明出处,否则将追究法律责任。