如题所述
以java为例,判断一个实体类是否为空代码如下:
/**判断对象或对象数组中每一个对象是否为空: 对象为null,字符序列长度为0,集合类、Map为empty */
public static boolean isNullOrEmpty(Object obj) {
if (obj == null)
return true;
if (obj instanceof CharSequence)
return ((CharSequence) obj).length() == 0;
if (obj instanceof Collection)
return ((Collection) obj).isEmpty();
if (obj instanceof Map)
return ((Map) obj).isEmpty();
if (obj instanceof Object[]) {
Object[] object = (Object[]) obj;
if (object.length == 0) {
return true;
}
boolean empty = true;
for (int i = 0; i < object.length; i++) {
if (!isNullOrEmpty(object[i])) {
empty = false;
break;
}
}
return empty;
}
return false;
}
扩展资料:
通过工具StringUtils的判断对象为空的两种方法:
1、org.apache.commons.lang3包;
2、org.springframework.util包。
这两种StringUtils工具类判断对象是否为空是区别:
StringUtils.isEmpty(CharSequence cs); //org.apache.commons.lang3包下的StringUtils类,判断是否为空的方法参数是字符序列类,即String类型;
StringUtils.isEmpty(Object str); //而org.springframework.util包下的参数是Object类,即不仅仅能判断String类型。
public class Test{
public static void main(String [] args){
Person p1 = new Person();
Person p2 = null;
System.out.println("p1实例 " + (p1 == null ? "" : "不") + "为空.");
System.out.println("p2实例 " + (p2 == null ? "" : "不") + "为空.");
}
}
class Person{
private String name;
public void setName(String name){
this.name=name;
}
}