在我们日常开发中,判空判空应该是推荐最常用的一个操作了。因此项目中总是判空少不了依赖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 int length(CharSequence cs) { return cs == null ? 0 : cs.length(); }这个方法除了判断字符串是否为null和长度是否为零,还判断了是判空否为空格,如果是推荐空格也返回true。
测试效果
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。
本文转载自微信公众号「Java旅途」,可以通过以下二维码关注。转载本文请联系Java旅途公众号。源码库