判空使⽤isEmpty()⽅法?这个开发常识你别说⾃⼰不知道在项⽬中,我们基本上都会有个StringUtils⼯具类,⽤来处理字符串相关的操作,⽐如:判空,长度,脱敏等。
今天有个⼩伙伴,因为调⽤别⼈提供的接⼝,接⼝⾥返回参数中有个String类型的。
⼩伙伴判空使⽤的是isEmpty()⽅法(⼤多数⼈认为这个⽅式没问题)。
但是问题来了:
接⼝返回的String类型参数不是空字符串,是个" "这样的字符串。
这个isEmpty⽅法居然返回成了false,那就是没问题了,校验通过了,然后⼊库了。于是后⾯的业务逻辑就乱了,接着整条业务线都被坑惨了!他的年终奖也就这么凉凉了~
其实我们在项⽬中处理⽅式⼀般有两种:
⼀种是⾃定义⼯具类,这个我们就不扯了。另外⼀种是使⽤第三⽅的⼯具类,⽐如:
commons-lang3中
org.apachemons.lang3.StringUtils。
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static boolean isBlank(final CharSequence cs) {空字符串是什么
final int strLen = length(cs);
if (strLen == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
spring-core中
org.springframework.util.StringUtils。
//判断是否为空
public static boolean isEmpty(Object str) {
return (str == null || "".equals(str));
}
//判断是否由内容
public static boolean hasText(String str) {
return (str != null && str.length() > 0 && containsText(str));
}
分析
上⾯两个第三⽅⼯具类的中isEmpty()⽅法判断是否为空,但是会有问题:如果其中存在" "这种字符串的时候,空⽩字符串是会认为不是空(业务代码中基本上都会把空⽩字符串处理成空,除⾮有⾮常特殊情况)。
isBlank()判断是否为空,处理了" "这种场景。所以如果项⽬中使⽤的是org.apachemons.lang3.StringUtils时,建议使⽤isBlank()⽅法。hasText()⽅法是判断是否存在内容,也处理了" "这种字符串,但是需要注意hasText()⽅法的返回值和isBlank()⽅法返回值是相反的。
⽰例
使⽤isEmpty()⽅法和isBlank()⽅法:
import org.apachemons.lang3.StringUtils;
public class StringUtilDemo {
public static void main(String[] args) {
String name = "";
String name0 = " ";
System.out.println(StringUtils.isEmpty(name));
System.out.println(StringUtils.isEmpty(name0));
System.out.println(StringUtils.isBlank(name));
System.out.println(StringUtils.isBlank(name0));
}
}
输出:
true
false
true
true
空⽩字符串就认为不是空了,但是往往我们在业务代码处理过程中,也需要把空⽩字符串当做是空来处理,所以在使⽤的时候回留点⼼。
但是isBlank()⽅法却避免了这种空⽩字符串的问题。
使⽤isEmpty()⽅法和hasText()⽅法:
import org.springframework.util.StringUtils;
public class StringUtilDemo {
public static void main(String[] args) {
String name = "";
String name0 = " ";
System.out.println(StringUtils.isEmpty(name));
System.out.println(StringUtils.isEmpty(name0));
System.out.println(StringUtils.hasText(name));
System.out.println(StringUtils.hasText(name0));
}
}
输出:
true
false
false
false
isEmpty()⽅法也会把空⽩字符串当做不是空字符串。但是hasText()⽅法却能避免空⽩字符串的问题。
总结
永远不要指望别⼈返回来的字符串绝对没有空⽩字符串。
不是不推荐使⽤isEmpty(),⽽是看你的业务代码⾥是否把空⽩字符串当做空字符串来处理。
如果空⽩字符串是按照空字符串查来处理,那么推荐使⽤isBlank()⽅法或者hasText()⽅法。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论