import org.apache.commons.lang3.StringUtils;
pom.xml中maven的依赖包
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
1.使用的过程中,小编首先想到的是isEmpty(), 结果进入源码进行阅读后,决定使用isBank().
有些朋友在Eclipse下并未进入源码。参考此网址,阅读源码:https://blog.csdn.net/qq_40615403/article/details/86171335
多阅读源码,对自己受益匪浅。
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) {
//字符串为空,或者字符串长度为0
return cs == null || cs.length() == 0;
}public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
isBank()
/**
* <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;//标记字符长度//字符串为空或者字符串长度为0
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {//isWhitespace() 方法用于判断指定字符是否为空白字符,空白符包含:空格、tab键、换行符。
//charAt()功能类似于数组,可以把字符串看作是char类型的数组,它是把字符串拆分获取其中的某个字符;返回指定位置的字符。
//charAt(i),i为int类型,i从0开始。
//判断空格,回车,换行等,如果有一个不是上述字符,就返回false
if (Character.isWhitespace(cs.charAt(i)) == false) {
return false;
}
}
return true;
}public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}//当受检查的值时 null 时,返回true,当受检查值时 ""时,返回值时true,当受检查值是空字符串时,返回值是true
在校验一个String类型的变量是否为空时,通常存在3中情况
- 是否为 null
- 是否为 ""
- 是否为空字符串(引号中间有空格) 如: " "。
StringUtils的isBlank()方法可以一次性校验这三种情况,返回值都是true
两个方法都是判断字符是否为空。前者是要求没有任何字符,即str==null 或 str.length()==0;后者要求是空白字符,即无意义字符。其实isBlank判断的空字符是包括了isEmpty的。isEmpty判断的范围更小点。