为了将非null属性从对象复制到另一个对象的助手 [英] Helper in order to copy non null properties from object to another

查看:85
本文介绍了为了将非null属性从对象复制到另一个对象的助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅以下课程

public class Parent {

    private String name;
    private int age;
    private Date birthDate;

    // getters and setters   

}

假设我创建了一个父对象,如下所示

Suppose I have created a parent object as follows

Parent parent = new Parent();

parent.setName("A meaningful name");
parent.setAge(20);

根据birthDate属性上面的代码的通知为null.现在,我只想将非空属性从父对象复制到另一个对象.像

Notice according to code above birthDate property is null. Now I want to copy only non-null properties from parent object to another. Something like

SomeHelper.copyNonNullProperties(parent, anotherParent);

我需要它,因为我想更新anotherParent对象而不用空值覆盖其非null值.

I need it because I want to update anotherParent object without overwriting its non-null with null values.

你知道像这样的帮手吗?

Do you know some helper like this one?

无论是否有帮助者,我都会接受最少的代码作为答案

I accept minimal code as answer whether no helper in mind

推荐答案

我想您已经有了一个解决方案,因为自您提出要求以来已经发生了很多时间.但是,它没有标记为已解决,也许我可以为其他用户提供帮助.

I supose you already have a solution, since a lot of time has happened since you asked. However, it is not marked as solved, and maybe I can help other users.

您是否尝试过定义org.commons.beanutils包的BeanUtilsBean的子类?实际上,BeanUtils使用此类,所以这是dfa提出的解决方案的改进.

Have you tried by defining a subclass of the BeanUtilsBean of the org.commons.beanutils package? Actually, BeanUtils uses this class, so this is an improvement of the solution proposed by dfa.

检查源代码该类中的代码,我认为您可以通过检查空值并覆盖空值来覆盖copyProperty方法.

Checking at the source code of that class, I think you can overwrite the copyProperty method, by checking for null values and doing nothing if the value is null.

类似这样的东西:

package foo.bar.copy;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtilsBean;

public class NullAwareBeanUtilsBean extends BeanUtilsBean{

    @Override
    public void copyProperty(Object dest, String name, Object value)
            throws IllegalAccessException, InvocationTargetException {
        if(value==null)return;
        super.copyProperty(dest, name, value);
    }

}

然后,您可以实例化NullAwareBeanUtilsBean并将其用于复制bean,例如:

Then you can just instantiate a NullAwareBeanUtilsBean and use it to copy your beans, for example:

BeanUtilsBean notNull=new NullAwareBeanUtilsBean();
notNull.copyProperties(dest, orig);

这篇关于为了将非null属性从对象复制到另一个对象的助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆