当前位置: 代码迷 >> 综合 >> BeanUtils.copyProperties在拷贝属性时忽略空值
  详细解决方案

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

热度:84   发布时间:2024-02-08 01:16:46.0

引用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));}}
  相关解决方案