Helper是为了将非null属性从对象复制到另一个? (JAVA) [英] Helper in order to copy non null properties from object to another ? (Java)

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

问题描述

参见以下课程

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 overrides 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.

您是否尝试过定义 BeanUtilsBean的子类

org.commons.beanutils 包的code>?实际上, 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 方法,如果值为null则不执行任何操作。

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);

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

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