开发中经常用到对象的copy,而BeanUtil工具类是大多数人copy对象的选择.很多时候,我们在copy时,需要排除掉源对象 属性为空的值,以免其覆盖目标对象的值,这时候就需要把源对象中属性为空的值找出来,工具类如下.
1.BeanUtil直接copy,可以把User对象的属性值都copy给User1,但是这样就把User1的nickName给覆盖为null了
public static void main(String[] args) {
User user = new User();
user.setName("李白");
user.setScore(80);
User user1 = new User();
user1.setNickName("啦啦");
BeanUtil.copyProperties(user,user1);
}
2.BeauUtil只copy源对象中属性非空的值
public static void main(String[] args) {
User user = new User();
user.setName("李白");
user.setScore(80);
User user1 = new User();
user1.setNickName("啦啦");
BeanUtil.copyProperties(user,user1,IgnorePropertiesUtil.getNullPropertyNames(user));
}
工具类:
public class IgnorePropertiesUtil {
public static String[] getNullPropertyNames(Object source) {
BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for (PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null)
emptyNames.add(pd.getName());
}
return emptyNames.toArray(new String[emptyNames.size()]);
}
}
BeanUtil源码:
/**
* Copy the property values of the given source bean into the given target bean,
* ignoring the given "ignoreProperties".
* <p>Note: The source and target classes do not have to match or even be derived
* from each other, as long as the properties match. Any bean properties that the
* source bean exposes but the target bean does not will silently be ignored.
* <p>This is just a convenience method. For more complex transfer needs,
* consider using a full BeanWrapper.
* @param source the source bean
* @param target the target bean
* @param ignoreProperties array of property names to ignore
* @throws BeansException if the copying failed
* @see BeanWrapper
*/
public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
copyProperties(source, target, null, ignoreProperties);
}