StringUtils.isBlank(),StringUtils.isEmpty()
以前没注意过,一直用StringUtils.isEmpty(),最近code review突然提到这个,所以记录一下。
StringUtils
首先说一下StringUtils这个类,StringUtils类中的方法的操作对象是 java.lang.String 类型的对象,属于org.apache.commons.lang3包,使用的话需要引入,maven项目引入如下
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
StringUtils.isEmpty()
先看一下源码
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
很明显,isEmpty()方法是对null和""的字符串返回true,对于空格,制表符等特殊字符,isEmpty()方法返回false。
StringUtils.isBlank()
先看一下源码
/**
* <p>Checks if a CharSequence is empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</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 only
* @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))) {
return false;
}
}
return true;
}
isBlank()方法,主要检查三种情况,第一,是否为null;第二,是否为"“,即空字符串;第三,是否为制表符,空格,换行符,换页符和回车。
针对第三种举个例子:
StringUtils.isBlank(”\t \n \f \r") = true,对于制表符,换行符,换页符,回车,该方法返回true。