看下面的课
public class Parent {
private String name;
private int age;
private Date birthDate;
// getters and setters
}
假设我创建了一个父对象如下
Parent parent = new Parent();
parent.setName("A meaningful name");
parent.setAge(20);
注意根据上面的代码,birthDate 属性为空。现在我只想将非空属性从父对象复制到另一个对象。类似的东西
SomeHelper.copyNonNullProperties(parent, anotherParent);
我需要它,因为我想更新 anotherParent 对象而不用 null 值覆盖它的非 null。
你知道像这样的 helper 吗?
我接受最少的代码作为答案,无论是否考虑到帮助
最佳答案
我想你已经有了解决方案,因为自从你问以来已经发生了很多时间。但是,它没有标记为已解决,也许我可以帮助其他用户。
您是否尝试过定义 org.commons.beanutils
包的 BeanUtilsBean
的子类?实际上,BeanUtils
使用了这个类,所以这是对dfa提出的方案的改进。
查看 source code对于那个类,我认为您可以覆盖 copyProperty
方法,方法是检查 null 值,如果值为 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,例如:
BeanUtilsBean notNull=new NullAwareBeanUtilsBean();
notNull.copyProperties(dest, orig);
关于java - 帮助器,以便将非空属性从对象复制到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1301697/