简单方法获取非空对象中的字段值并设置为同一类的另一个对象

时间:2014-06-11 07:14:15

标签: java javabeans

在下面的代码中,我有两个相同类的对象。一个对象(A - employeeObjectInDatabase)设置了所有字段。另一个对象(B - employeeObjectForUpdate)只设置了很少的字段。基本上我需要将对象B的非空值设置为对象A.下面的代码有'if not null'检查每个字段来设置值。还有其他更好的办法来完成这项工作吗?

有没有更好的方法来替换注释“BLOCK 1 BEGIN”和“BLOCK 1 END”之间的代码?

对于包含少量字段的类,检查if not not是否容易,但是如果有20多个字段,则需要进行大量if if null检查,因此想到获得专家意见。

样品:

public class Employee {

    private String id;

    private String name;

    private String department;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }


    public static void main(String[] args) {

        Employee newEmployeeObject = new Employee();
        newEmployeeObject.setId("A100");
        newEmployeeObject.setName("Albert");
        newEmployeeObject.setName("Physics");

        //newEmployeeObject is persisted into database

        Employee employeeObjectForUpdate = new Employee();
        employeeObjectForUpdate.setId("A100");
        employeeObjectForUpdate.setName("Albert Einstein");

        //Inorder to update only the fields that are not null

        Employee employeeObjectInDatabase = employeeDao.getEmployee();

        //BLOCK 1 BEGIN
        if (null != employeeObjectForUpdate.getName())
            employeeObjectInDatabase.setName(employeeObjectForUpdate.getName());

        if (null != employeeObjectForUpdate.getDepartment())
            employeeObjectInDatabase.setDepartment(employeeObjectForUpdate.getDepartment());

        //BLOCK 1 END

        //persist employeeObjectInDatabase as it has the updated information
    }
}

4 个答案:

答案 0 :(得分:1)

您可以在setter方法中移动空检查

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

然后在您的main方法中,您可以简单地调用以下内容: employeeObjectInDatabase.setName(employeeObjectForUpdate.getName());

如果在数据访问层中将db值填充到对象时,将应用相同的原则。也就是说,如果Db列值为null,则不会将其设置为属性

答案 1 :(得分:1)

您可以创建一个成员方法,使用反射将非空字段值传输到相同类型的给定对象。

答案 2 :(得分:1)

以下显示了使用org.apache.commons.beanutils.BeanUtilsBean的解决方案。看看它是否有帮助。

Helper in order to copy non null properties from object to another ? (Java)

答案 3 :(得分:0)

将复制方法添加到对象B.此方法应将其非空值复制到对象A并将其返回。此方法也可以在此方法中使用反射。

看看这篇文章;

Copy all values from fields in one class to another through reflection