通过此工具类,除了对象的空和非空判断使用isNull、isNotNull,其他类型(String、List、Map等)的判断均可通过isEmpty、isNotEmpty搞定,提高业务代码中空与非空判断的简洁性和可读性。
import java.util.*;
/**
* 空和非空判断工具类
*/
public class CommonEmptyUtils
{
/** 空字符串 */
private static final String EMPTY_STR = "";
/**
* 判断对象是否为空
*
* @param object 对象参数
* @return true:空,false:非空
*/
public static boolean isNull(Object object)
{
return object == null;
}
/**
* 判断对象是否非空
*
* @param object 对象参数
* @return true:非空,false:空
*/
public static boolean isNotNull(Object object)
{
return !isNull(object);
}
/**
* 判断Collection是否为空, 包含List,Queue,Set
*
* @param coll 集合参数
* @return true:为空,false:非空
*/
public static boolean isEmpty(Collection<?> coll)
{
return isNull(coll) || coll.isEmpty();
}
/**
* 判断Collection是否非空,包含List,Queue,Set
*
* @param coll 集合参数
* @return true:非空,false:空
*/
public static boolean isNotEmpty(Collection<?> coll)
{
return !isEmpty(coll);
}
/**
* 判断对象数组是否为空
*
* @param objects 对象数组参数
** @return true:为空,false:非空
*/
public static boolean isEmpty(Object[] objects)
{
return isNull(objects) || (objects.length == 0);
}
/**
* 判断对象数组是否非空
*
* @param objects 对象数组参数
* @return true:非空,false:空
*/
public static boolean isNotEmpty(Object[] objects)
{
return !isEmpty(objects);
}
/**
* 判断一个Map是否为空
*
* @param map Map参数
* @return true:为空,false:非空
*/
public static boolean isEmpty(Map<?, ?> map)
{
return isNull(map) || map.isEmpty();
}
/**
* 判断一个Map是否为空
*
* @param map Map参数
* @return true:非空,false:空
*/
public static boolean isNotEmpty(Map<?, ?> map)
{
return !isEmpty(map);
}
/**
* 判断字符串是否为空串
*
* @param str String参数
* @return true:为空,false:非空
*/
public static boolean isEmpty(String str)
{
return isNull(str) || EMPTY_STR.equals(str.trim());
}
/**
* 判断字符串是否为非空串
*
* @param str String参数
* @return true:非空串,false:空串
*/
public static boolean isNotEmpty(String str)
{
return !isEmpty(str);
}
}