乙個較共通工具類判斷物件是否為空

2021-10-01 12:45:29 字數 1630 閱讀 5744

背景:在實際的專案中,我們在使用變數之前都會進行安全性的非空校驗,簡單的寫乙個非空判斷工具類還是蠻okay。

工具類如下:

public class nonemptyutils , this method at first time validates whether its' length is zero

* because is the most common.

* for , this method only validate its' size whether it is zero

* for , this method only validate its' size whether it is zero

* for , this method only validate its' size whether it is zero

** if you want to validate every element in ,,

* @param obj

* @return boolean

*/public static boolean shallowvalidatenullorempty(object obj)else if(obj instanceof string)

}else if(obj instanceof map)

}else if(obj instanceof collection)

}else if(obj.getclass().isarray())

}return false;

}}

這裡有兩個注意點,

第一,對array型別的非空判斷,應當使用 obj.getclass().isarray(), 而不能使用 obj instanceof object。

因為引用型別陣列,new boolean[0], 使用obj instanceof object返回true;new boolean[0],使用obj instanceof object返回false。即obj instanceof object僅僅適用引用型別陣列。

第二,不建議將內層if條件和外層if條件合併在一起,這樣影響效率。雖然看起來第一種方式和第二種方式效果一樣,都能達到目的並且簡化了**。但是如果非空字串「aabb」,走第一種方式,在第一次if判斷 obj instanceof string1,程式就跳出去。走第二張方式,不僅會第一次if判斷obj instanceof string1,也會第二次if判斷obj instanceof string2,以此類推。如果有大量的if else,第二種就會多次無效地判斷後面所有的if條件。

// correct

// first way

if(obj == null)else if(obj instanceof string1)

}else if(obj instanceof string2)

}// wrong

// second way

if(obj == null)else if(obj instanceof string1 && ((string1) obj).length() == 0)else if(obj instanceof string2 && ((string2) obj).length() == 0)

判斷乙個物件是否為陣列

方法一 使用instanceof操作符。instanceof操作符用來判斷要檢測物件的原型鏈上是否存在某個建構函式的prototype屬性。var a var b console.log a instanceof object true console.log b instanceof object...

判斷乙個物件是否為空

for var i in obj return true 為空 if json stringfy obj else if object.keys obj length 0 else 陣列var arr 1 34 89 0 var arr 1 34 89 0 for var value of arr ...

判斷乙個物件是否為Buffer物件

1 問題背景 不同資料型別物件變數,如何判斷乙個物件是否為buffer物件 2 實現原始碼 you anikdjfijkfjkdsjfkdjfkdjfkdjfkdjfkd anikdjfijkfjkdsjfkdjfkdjfkdjfkdjfkd hai buffer 128 typeof you st...