BeanUtils.copyProperties在拷贝属性时忽略空值

引用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 

获取到对象中属性为null的属性名

* @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

拷贝非空对象属性值

* @param source 源对象 * @param target 目标对象 */
public static void copyPropertiesIgnoreNull(Object source, Object target) { BeanUtils.copyProperties(source, target, getNullPropertyNames(source)); } }

你可能感兴趣的:(java)