在我们日常开发中,判空应该是最常用的一个操作了。因此项目中总是少不了依赖commons-lang3包。这个包为我们提供了两个判空的方法,分别是StringUtils.isEmpty(CharSequence cs)和StringUtils.isBlank(CharSequence cs)。我们分别来看看这两个方法有什么区别。
isEmpty的源码如下:
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}这个方法判断的是字符串是否为null或者其长度是否为零。
「测试效果」
public class BlankAndEmpty {
public static void main(String[] args) {
System.out.println(StringUtils.isEmpty(null)); // true
System.out.println(StringUtils.isEmpty("")); //true
System.out.println(StringUtils.isEmpty(" ")); //false
System.out.println(StringUtils.isEmpty("\t")); //false
System.out.println(StringUtils.isEmpty("Java旅途")); //false
}
}isBlank的源码如下:
public static boolean isBlank(CharSequence cs) { int strLen = length(cs); if (strLen == 0) { return true; } else { for(int i = 0; i < strLen; ++i) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } }
return true; }}length(cs)的方法如下
public static boolean isBlank(CharSequence cs) {
int strLen = length(cs);
if (strLen == 0) {
return true;
} else {
for(int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
}这个方法除了判断字符串是否为null和长度是否为零,还判断了是否为空格,如果是空格也返回true。
「测试效果」
public static int length(CharSequence cs) {
return cs == null ? 0 : cs.length();
}public class BlankAndEmpty {
public static void main(String[] args) {
System.out.println(StringUtils.isBlank(null)); //true
System.out.println(StringUtils.isBlank("")); //true
System.out.println(StringUtils.isBlank(" ")); //true
System.out.println(StringUtils.isBlank("\t")); //true
System.out.println(StringUtils.isBlank("Java旅途")); //false
}
}这个工具类的优点很明显,一方面判断了字符串“null”,另一方面对参数个数无限制,只要有一个参数是空则返回true。