Java object copy non-empty properties

Refer to the method copyProperties(Object source, Object target, String... ignoreProperties)  provided by the org.springframework.beans.BeanUtils class  for object copying. Both spring and Apache provide corresponding tool class methods, 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>Get the attribute name whose attribute is null in the object</P> 
     * @param source The object to be copied 
     * @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> Copy the property value of a non-empty object</ P> 
     * @param source source object 
     * @param target target object 
     */ 
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source)); 
    } 

}

 

Refer to https://blog.csdn.net/zml_2015/article/details/55192785

Guess you like

Origin blog.csdn.net/qq_36961530/article/details/87917247