zl程序教程

您现在的位置是:首页 >  其他

当前栏目

盘点Spring源码中的那些判空

2023-04-18 16:56:48 时间

Spring源码中的那些判空

背景 & 介绍

在平时进行判空时, 相信很多人使用的都是 org.apache.commons.lang3 的StringUtils 而我在阅读Spring源码中, 发现了一个宝藏. springframework 中自带的StringUtils, 而且也可以进行判空

首先我们可以看下commons包下面的StringUtils的源码, 可以看到

  1. isEmpty() 的作用是判断输入的字符串是否为null 或者 字符串长度为0 , 例如: null, “” (空字符串)
  2. isBlank() 的作用是在 isEmpty()的基础上追加对空白符的判空, 例如 " " (空格符), " ", " "(tab)等.
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isNotEmpty(CharSequence cs) {
        return !isEmpty(cs);
    }

    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }
    
	public static boolean isNotBlank(CharSequence cs) {
	        return !isBlank(cs);
	    }

然后我们再来看 Springframework 自带的 StringUtils 源码

  1. 可以看到该工具类中也有isEmpty() 方法, 但是入参接收的是Object类型的, 可能存在转换异常. 因此不建议使用
  2. 这里的 hasLength() 相当于 commons下的 !isEmpty()isNotEmpty. 表示该String是有长度/内容的
  3. 这里的 hasText() 相当于 commons下的 !isBlank()isNotBlank()
	public static boolean isEmpty(@Nullable Object str) {
		return (str == null || "".equals(str));
	}
	
	public static boolean hasLength(@Nullable String str) {
		return (str != null && !str.isEmpty());
	}

	public static boolean hasText(@Nullable String str) {
		return (str != null && !str.isEmpty() && containsText(str));
	}

	private static boolean containsText(CharSequence str) {
		int strLen = str.length();
		for (int i = 0; i < strLen; i++) {
			if (!Character.isWhitespace(str.charAt(i))) {
				return true;
			}
		}
		return false;
	}

结论 & 使用方式举例

结论

如果我们仅仅是使用StringUtils的判空操作的话, 完全可以不用引入 org.apache.common的jar. 而使用spring原生的工具类进行判空

使用方式

  • hasLength() 相当于 commons下的 !isEmpty()isNotEmty()
  • hasText() 相当于 commons下的 !isBlank()isNotBlank()
  • 使用上述方式能够无形的展示你看过源码, 让后来者佩服(臆想ing~~)

举例:

唉? 等等 在我找源码中使用springframework中StringUtils的举例时, 发现了了一个 isEmpty(), 但是这个判空不是对String类型进行判空, 而是对list集合进行的判空, 然后把鼠标放到该方法, 结果令我大喜过望 这个包下面就有一个对 list 集合判空的方法, 他的作用是: 如果list 没有元素它将返回 true

查看了一下底层源码, 是通过对list集合元素个数进行判断从而达到判空的效果.

    public boolean isEmpty() {
        return size() == 0;
    }

然后我们可以和我经常使用的 import org.springframework.util.CollectionUtils 下的集合判空方法对比, 可以看到该工具类相比上面集合自带的方法, 多了一个为null 时候的判断, 而这种情况就是防止在初始化时候或者数据为查询到的时候设置为null的情况. 如果在null的情况下直接调用集合自带的isEmpty()则会报空指针异常. 因此在进行集合判空时, 建议使用 CollectionUtils.isEmpty(集合) 进行判空 果然源码教我们做人~~~

    public static boolean isEmpty(@Nullable Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }
   public boolean isEmpty() {
        return size() == 0;
    }