Java对象复制非空属性

引用org.springframework.beans.BeanUtils类提供的方法copyProperties(Object source, Object target, String... ignoreProperties)  用于对象拷贝,spring 和 Apache都提供了相应的工具类方法,BeanUtils.copyProperties

package com.mixislink.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author WuSong
 * @Date 2019-02-25
 * @Time 14:30:37
 */
public class BeansUtil {
    /**
     * @Description <p>获取到对象中属性为null的属性名  </P>
     * @param source 要拷贝的对象
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * @Description <p> 拷贝非空对象属性值 </P>
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

}

参考https://blog.csdn.net/zml_2015/article/details/55192785

猜你喜欢

转载自blog.csdn.net/qq_36961530/article/details/87917247