首頁>技術>

在專案中,我們基本上都會有個StringUtils工具類,用來處理字串相關的操作,比如:判空,長度,脫敏等。

今天有個小夥伴,因為呼叫別人提供的介面,接口裡返回引數中有個String型別的。

小夥伴判空使用的是isEmpty()方法(大多數人認為這個方式沒問題)。

但是問題來了:

介面返回的String型別引數不是空字串,是個" "這樣的字串。

這個isEmpty方法居然返回成了false,那就是沒問題了,校驗通過了,然後入庫了。於是後面的業務邏輯就亂了,接著整條業務線都被坑慘了!他的年終獎也就這麼涼涼了~

其實我們在專案中處理方式一般有兩種:

一種是自定義工具類,這個我們就不扯了。另外一種是使用第三方的工具類,比如:

commons-lang3中

org.apache.commons.lang3.StringUtils。

public static boolean isEmpty(final CharSequence cs) {      return cs == null || cs.length() == 0;}public static boolean isBlank(final CharSequence cs) {    final int strLen = length(cs);    if (strLen == 0) {        return true;    }    for (int i = 0; i < strLen; i++) {        if (!Character.isWhitespace(cs.charAt(i))) {            return false;        }    }    return true;}
spring-core中

org.springframework.util.StringUtils。

//判斷是否為空public static boolean isEmpty(Object str) {  return (str == null || "".equals(str));}//判斷是否由內容public static boolean hasText(String str) {  return (str != null && str.length() > 0 && containsText(str));}
分析

上面兩個第三方工具類的中isEmpty()方法判斷是否為空,但是會有問題:如果其中存在" "這種字串的時候,空白字串是會認為不是空(業務程式碼中基本上都會把空白字串處理成空,除非有非常特殊情況)。

isBlank()判斷是否為空,處理了" "這種場景。所以如果專案中使用的是org.apache.commons.lang3.StringUtils時,建議使用isBlank()方法

hasText()方法是判斷是否存在內容,也處理了" "這種字串,但是需要注意hasText()方法的返回值和isBlank()方法返回值是相反的。

示例

使用isEmpty()方法和isBlank()方法:

import org.apache.commons.lang3.StringUtils;public class StringUtilDemo {    public static void main(String[] args) {        String name = "";        String name0 = " ";        System.out.println(StringUtils.isEmpty(name));        System.out.println(StringUtils.isEmpty(name0));        System.out.println(StringUtils.isBlank(name));        System.out.println(StringUtils.isBlank(name0));    }}

輸出:

truefalsetruetrue

空白字串就認為不是空了,但是往往我們在業務程式碼處理過程中,也需要把空白字串當做是空來處理,所以在使用的時候會留點心。

但是isBlank()方法卻避免了這種空白字串的問題。

使用isEmpty()方法和hasText()方法:

import org.springframework.util.StringUtils;public class StringUtilDemo {    public static void main(String[] args) {        String name = "";        String name0 = " ";        System.out.println(StringUtils.isEmpty(name));        System.out.println(StringUtils.isEmpty(name0));        System.out.println(StringUtils.hasText(name));        System.out.println(StringUtils.hasText(name0));    }}

輸出:

truefalsefalsefalse

isEmpty()方法也會把空白字串當做不是空字串。但是hasText()方法卻能避免空白字串的問題。

總結

永遠不要指望別人返回來的字串絕對沒有空白字串。

不是不推薦使用isEmpty(),而是看你的業務程式碼裡是否把空白字串當做空字串來處理。

如果空白字串是按照空字串查來處理,那麼推薦使用isBlank()方法或者hasText()方法。

9
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • SpringCloud 2020.0.0釋出,全新顛覆性版本