先看两个源码:
这个是StringUtils.isBlank()源码
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; } }
这个是StringUtils.isEmpty()源码
public static boolean isEmpty(CharSequence cs) { return cs == null || cs.length() == 0; }
从中可以发现
-
StringUtils.isEmpty()
方法:- 用于检查字符串是否为
null
或者长度是否为0。 - 如果字符串为
null
或者长度为0,则返回true
;否则返回false
。 - 例如,对于字符串
""
或者null
,StringUtils.isEmpty()
方法都会返回true
。
- 用于检查字符串是否为
-
StringUtils.isBlank()
方法:- 用于检查字符串是否为
null
或者长度为0,或者字符串中只包含空格。 - 如果字符串为
null
或者长度为0,或者字符串中只包含空格(包括全角空格等),则返回true
;否则返回false
。 - 例如,对于字符串
" "
或者"\t\n\r"
,StringUtils.isBlank()
方法会返回true
,而StringUtils.isEmpty()
方法会返回false
。
- 用于检查字符串是否为
因此,StringUtils.isBlank()
方法相比 StringUtils.isEmpty()
方法多了一项判断,即字符串中是否只包含空白字符。选择使用哪个方法取决于具体的业务逻辑需求。