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 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.apachemons.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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。