1.直接判断当前对象是否为空,可以直接用下面的方式
package com.cn.util;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class ToolUtil {
/**
* 判断对象是否为空
*
* @param o 需要判断的对象
* @return 为空返回true, 不为空返回false
*/
@SuppressWarnings("rawtypes")
public static boolean isEmpty(Object o) {
if (o == null || Objects.isNull(o)) {
return true;
}
if (o instanceof String) {
if ("".equals(o.toString().trim())) {
return true;
}
return "undefined".equals(o.toString().trim());
} else if (o instanceof List) {
return ((List) o).size() == 0;
} else if (o instanceof Map) {
return ((Map) o).size() == 0;
} else if (o instanceof Set) {
return ((Set) o).size() == 0;
} else if (o instanceof Object[]) {
return ((Object[]) o).length == 0;
} else if (o instanceof int[]) {
return ((int[]) o).length == 0;
} else if (o instanceof long[]) {
return ((long[]) o).length == 0;
}
return false;
}
}
2.当前端以json方式传值,并且json为空时,后台以对象的方式接收@RequestBody
可以用以下的方式判断是否为空
public boolean isAllFieldNull(Object obj) throws Exception{
//字节码对象
Class stuCla = (Class) obj.getClass();
//在Java反射中Field类描述的是类的属性信息
Field[] fs = stuCla.getDeclaredFields();
boolean flag = true;
for (Field f : fs) {
//直接获取对象中的所有参数
f.setAccessible(true);
Object val = f.get(obj);
if(!ToolUtil.isEmpty(val)) {
flag = false;
break;
}
}
return flag;
}