Java Bean 属性复制
一:""也进行复制
package com.wing.ihome.cloud.core.util; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.util.StringUtils; import java.util.HashSet; import java.util.Set; /** * 解决BeanUtils.copyProperties复制null属性的问题 */ public class CopyUtils { /** * BeanUtils.copyProperties(source, target, getNullPropertyNames(source)); * 可忽略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<>(); for (java.beans.PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (StringUtils.isEmpty(srcValue)) { emptyNames.add(pd.getName()); } } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); } }
使用:
BeanUtils.copyProperties(inpUserParam, user, CopyUtils.getNullPropertyNames(inpUserParam));
inpUserParam 要传递者
user 被传递者