StringUtils工具类isBlank方法

StringUtils.isEmpty

我们先来看org.springframework.util.StringUtils包下的isEmpty()方法,

/**
     * Check whether the given object (possibly a {@code String}) is empty.
     * This is effectively a shortcut for {@code !hasLength(String)}.
     * <p>This method accepts any Object as an argument, comparing it to
     * {@code null} and the empty String. As a consequence, this method
     * will never return {@code true} for a non-null non-String object.
     * <p>The Object signature is useful for general attribute handling code
     * that commonly deals with Strings but generally has to iterate over
     * Objects since attributes may e.g. be primitive value objects as well.
     * <p><b>Note: If the object is typed to {@code String} upfront, prefer
     * {@link #hasLength(String)} or {@link #hasText(String)} instead.</b>
     * @param str the candidate object (possibly a {@code String})
     * @since 3.2.1
     * @see #hasLength(String)
     * @see #hasText(String)
     */
    public static boolean isEmpty(@Nullable Object str) {
        return (str == null || "".equals(str));
    }

这是源码部分,可以看到isEmpty方法当参数为字符串时只能判断为null或者为"",

String str = " ";
System.out.println(StringUtils.isEmpty(str));

 当这种时返回结果为false;

在判断一个String类型的变量是否为空时,有三种情况

  • 是否为null
  • 是否为""
  • 是否为”  “
org.apache.commons.lang3.StringUtils包里的isBlank方法
我们先看源码
/**
     * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
     *
     * <pre>
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * </pre>
     *
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is null, empty or whitespace
     * @since 2.0
     * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
     */
    public static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (Character.isWhitespace(cs.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }

可以看到官方给我们举得例子:‘先判断是否为null和长度是否为0

StringUtils.isBlank(null)    = true
StringUtils.isBlank("")      = true
StringUtils.isBlank(" ")     = true
posted @ 2020-10-26 14:32  木马不是马  阅读(2247)  评论(0编辑  收藏  举报