判空工具类

在项目中经常会用到对空的判断,本方法将空判断进行集中,作为工具使用。

可减少代码量,并使代码更加优雅。

  1 import java.lang.reflect.Array;
  2 import java.util.ArrayList;
  3 import java.util.Collection;
  4 import java.util.List;
  5 import java.util.Map;
  6 
  7 /**
  8  * <p> 空判断工具类 </p>
  9  *
 10  * @author lijinghao
 11  * @version v 0.1
 12  * @date 2018-06-14 18:56:33
 13  */
 14 public class EmptyUtil {
 15 
 16     public static final String EMPTY = "";
 17 
 18     /**
 19      * 判断对象是否为空
 20      * 对于Collection,Array,Map,String 会进行长度的空判断
 21      *
 22      * @param obj 对象
 23      * @return {@code true}: 为空<br>{@code false}: 不为空
 24      */
 25     public static boolean isEmpty(Object obj) {
 26         if (obj == null) {
 27             return true;
 28         }
 29         if (obj instanceof String && obj.toString().length() == 0) {
 30             return true;
 31         }
 32         if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
 33             return true;
 34         }
 35         if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
 36             return true;
 37         }
 38         if (obj instanceof Map && ((Map) obj).isEmpty()) {
 39             return true;
 40         }
 41 
 42         return false;
 43     }
 44 
 45     /**
 46      * 判断字符串是否为空
 47      * 当字符串为 null, 空串或纯空格时,返回true
 48      *
 49      * @param str 字符串
 50      * @return {@code true}: 为空<br>{@code false}: 不为空
 51      */
 52     public static boolean isEmptyStrTrim(String str ) {
 53         if (str == null) {
 54             return true;
 55         }
 56 
 57         if(str.trim().length() == 0){
 58             return true;
 59         }
 60 
 61         return false;
 62     }
 63 
 64     /**
 65      * 判断字符串是否为空
 66      * 当字符串不为 null, 空串或纯空格时,返回true
 67      *
 68      * @param str 字符串
 69      * @return {@code true}: 为空<br>{@code false}: 不为空
 70      */
 71     public static boolean isNotEmptyStrTrim(String str ) {
 72         return !isEmptyStrTrim(str);
 73     }
 74 
 75     /**
 76      * 判断对象是否非空
 77      *
 78      * @param obj 对象
 79      * @return {@code true}: 非空<br>{@code false}: 空
 80      */
 81     public static boolean isNotEmpty(Object obj) {
 82         return !isEmpty(obj);
 83     }
 84 
 85     /**
 86      * 判断对象是否非Null
 87      *
 88      * @param obj 对象
 89      * @return {@code true}: 非空<br>{@code false}: 空
 90      */
 91     public static boolean isNotNull(Object obj) {
 92         return !isNull(obj);
 93     }
 94     /**
 95      * 判断对象是否Null
 96      *
 97      * @param obj 对象
 98      * @return {@code true}: 空<br>{@code false}: 非空
 99      */
100     public static boolean isNull(Object obj) {
101         return obj == null;
102     }
103 
104 
105 }

猜你喜欢

转载自www.cnblogs.com/lthaoshao/p/9184569.html