Java 判断实体对象及所有属性是否为空

1、判断实体对象是否为空

2、判断对象所有属性是否为空

3、特别注意,实体类中如果有基本数据类型,会影响判断

package com.liuxd.object;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * Created by Liuxd on 2018/11/2.
 */
public class TestEntity {

    public static void main(String[] args) {
        User user1 = new User("Jack", "male", 17);
        User user2 = new User();

        boolean u1Flag = checkObjAllFieldsIsNull(user1);
        boolean u2Flag = checkObjAllFieldsIsNull(user2);

        System.out.println("user1 是否为空:" + u1Flag);
        System.out.println("user2 是否为空:" + u2Flag);

    }

    /**
     * 判断对象中属性值是否全为空
     *
     * @param object
     * @return
     */
    public static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }

        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);

                System.out.print(f.getName() + ":");
                System.out.println(f.get(object));

                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }
}

实体类:

package com.liuxd.object;

/**
 * Created by Liuxd on 2018/11/2.
 */
public class User {

    private String name;

    private String gender;

    /**
     * 如果属性类型为基本数据类型,则会有默认值
     * 影响正确判断,请特别注意
     */
//  private int age;

    private Integer age;

    public User() {
    }

    public User(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

输出结果:

name:Jack
name:null
gender:null
age:null
user1 是否为空:false
user2 是否为空:true

你可能感兴趣的:(JAVA基础,解决方案,细说Java)