总结了很多的工具类
直接上代码
package com.dz.three.utils;
import org.springframework.lang.Nullable;
import java.lang.reflect.Array;
import java.util.*;
/**
* 所有的非空判断工具类
* create by dz
* 202-07-27
*/
public class NullUtils {
/**
* 可以判断任意值
*/
public static boolean isEmpty(Object obj) {
if (obj == null) return true;
else if (obj instanceof CharSequence) return ((CharSequence) obj).length() == 0;
else if (obj instanceof Collection) return ((Collection) obj).isEmpty();
else if (obj instanceof Map) return ((Map) obj).isEmpty();
else if (obj.getClass().isArray()) return Array.getLength(obj) == 0;
return false;
}
/**
* flag 为true使用trim判断
* 使用trim去空判断
*/
public static final boolean isNotEmptyString(String value, Boolean flag) {
if (flag) {
return !(value == null || value.trim().length() == 0 || "".equals(value));
} else {
return isNotEmptyString(value);
}
}
/**
* 检测某个字符变量是否不为空
* 判断 非空 ,长度大于0 ,不等于空串
*/
public static final boolean isNotEmptyString(final CharSequence value) {
return !(value == null || value.length() == 0 || "".equals(value));
}
/**
* 检测某个list是否不为空
* 方法一(数据量大,效率低):
* if(list != null && list.size() > 0){
* 方法二(数据量大,效率高):
* if(list != null && !list.isEmpty()){
* 所以判断list里是否有元素的最佳的方法是:
* if(list != null && !list.isEmpty()){
*/
public static final boolean isNotEmptyList(@Nullable Collection<?> list) {
return !(list == null || list.isEmpty());
}
/**
* 检测map是否不为空
* 判断 非空 ,长度大于0 ,不等于空串
*/
public static final boolean isNotEmptyMap(@Nullable Map<?, ?> map) {
return !(map == null || map.isEmpty());
}
/**
* 过滤字符
*/
public static String trimAll(String str) {
return str.trim()
.replaceAll("[ *| *| *|//s*]*", "")
.replaceAll("^[ *| *| *|//s*]*", "")
.replaceAll("[ *| *| *|//s*]*$", "");
}
/**
* 数组判断不为空,没有泛型数组,所以还是分开写吧
*
* @param arrs 可以是int,short,byte,String,Object,long
* @return
*/
public static boolean isNotEmptyArrs(int[] arrs) {
return arrs != null && arrs.length > 0;
}
/**
* 数组判断不为空,没有泛型数组,所以还是分开写吧
*/
public static boolean isNotEmptyArrs(String[] arrs) {
return arrs != null && arrs.length > 0;
}
public static void main(String[] args) {
// System.out.println(NullUtils.isNotEmptyString(" ", true));
// System.out.println(NullUtils.isNotEmptyString("1 "));
List<String> list = new ArrayList<>();
// StringUtils.isNotBlank()
list.add("56");
// System.out.println(NullUtils.isNotEmptyList(list));
Map<String, Object> map = new HashMap<>();
map.put("1", list);
System.out.println(NullUtils.isNotEmptyMap(map));
System.out.println(!NullUtils.isEmpty(map));
}
}