java 如何復制非空對象屬性值

java 復制非空對象屬性值

很多時候,我們需要通過對象拷貝,比如說VO類與數據庫實體bean類、更新時非空對象不更新,對同一對象不同數據分開存儲等

用於對象拷貝,spring 和 Apache都提供瞭相應的工具類方法,BeanUtils.copyProperties

但是對於非空屬性拷貝就需要自己處理瞭

在這裡借用spring中org.springframework.beans.BeanUtils類提供的方法

copyProperties(Object source, Object target, String… ignoreProperties)

/**
     * Copy the property values of the given source bean into the given target bean,
     * ignoring the given "ignoreProperties".
     * <p>Note: The source and target classes do not have to match or even be derived
     * from each other, as long as the properties match. Any bean properties that the
     * source bean exposes but the target bean does not will silently be ignored.
     * <p>This is just a convenience method. For more complex transfer needs,
     * consider using a full BeanWrapper.
     * @param source the source bean
     * @param target the target bean
     * @param ignoreProperties array of property names to ignore
     * @throws BeansException if the copying failed
     * @see BeanWrapper
     */
    public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
        copyProperties(source, target, null, ignoreProperties);
 
/**
     * Copy the property values of the given source bean into the given target bean.
     * <p>Note: The source and target classes do not have to match or even be derived
     * from each other, as long as the properties match. Any bean properties that the
     * source bean exposes but the target bean does not will silently be ignored.
     * @param source the source bean
     * @param target the target bean
     * @param editable the class (or interface) to restrict property setting to
     * @param ignoreProperties array of property names to ignore
     * @throws BeansException if the copying failed
     * @see BeanWrapper
     */
    private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties)
            throws BeansException {
 
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
 
        Class<?> actualEditable = target.getClass();
        if (editable != null) {
            if (!editable.isInstance(target)) {
                throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
                        "] not assignable to Editable class [" + editable.getName() + "]");
            }
            actualEditable = editable;
        }
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
 
        for (PropertyDescriptor targetPd : targetPds) {
            Method writeMethod = targetPd.getWriteMethod();
            if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
                    Method readMethod = sourcePd.getReadMethod();
                    if (readMethod != null &&
                            ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                        try {
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }
                            Object value = readMethod.invoke(source);
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }
                        catch (Throwable ex) {
                            throw new FatalBeanException(
                                    "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                        }
                    }
                }
            }
        }
    }

然後封裝一下得到以下方法

/**
     * @author zml2015
     * @Email [email protected]
     * @Time 2017年2月14日 下午5:14:25
     * @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);
    }
 
    /**
     * @author zml2015
     * @Email [email protected]
     * @Time 2017年2月14日 下午5:15:30
     * @Description <p> 拷貝非空對象屬性值 </P>
     * @param source 源對象
     * @param target 目標對象
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

測試方法就不提供瞭,自行測試即可

如果項目中使用的框架有Hibernate的話,則可以通過在實體類上添加下面兩條註解

@DynamicInsert(true)
@DynamicUpdate(true)

如果想對該註解進一步瞭解的話,那麼可以去官網看英文文檔,文檔解釋的很清楚,在此不再贅述瞭

java對象屬性復制的幾種方式

1.使用java反射機制

獲取對象的屬性和get、set方法進行復制;

2.使用spring-beans5.0.8包中的BeanUtils類

import org.springframework.beans.BeanUtils;
SourceObject sourceObject = new SourceObject();
TargetObject targetObject = new TargetObject();
BeanUtils.copyProperties(sourceObject, targetObject);

3.使用cglib3.2.8包中的net.sf.cglib.beans.BeanCopier類

import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.core.Converter;
SourceObject sourceObject = new SourceObject();
TargetObject targetObject = new TargetObject();
BeanCopier beanCopier = BeanCopier.create(SourceObject.class, TargetObject.class, true);--第三個參數表示是否使用轉換器,false表示不使用,true表示使用
Converter converter = new CopyConverter();--自定義轉換器
beanCopier.copy(sourceObject, targetObject, converter);

轉換器(當源對象屬性類型與目標對象屬性類型不一致時,使用轉換器):

import net.sf.cglib.core.Converter;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.util.Date;
/**
 * Created by asus on 2019/7/12.
 */
public class CopyConverter implements Converter {
    @Override
    public Object convert(Object value, Class target, Object context) {
        {
            String s = value.toString();
            if (target.equals(int.class) || target.equals(Integer.class)) {
                return Integer.parseInt(s);
            }
            if (target.equals(long.class) || target.equals(Long.class)) {
                return Long.parseLong(s);
            }
            if (target.equals(float.class) || target.equals(Float.class)) {
                return Float.parseFloat(s);
            }
            if (target.equals(double.class) || target.equals(Double.class)) {
                return Double.parseDouble(s);
            }
            if(target.equals(Date.class)){
                while(s.indexOf("-")>0){
                    s = s.replace("-", "/");
                }
                return  new Date(s);
            }
            if(target.equals(BigDecimal.class)){
                if(!StringUtils.isEmpty(s)&&!s.equals("NaN")){
                    return  new BigDecimal(s);
                }
            }
            return value ;
        }
    }
}

4.使用spring-core5.0.8包

中的org.springframework.cglib.beans.BeanCopier類(用法與第三種一樣)

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;
SourceObject sourceObject = new SourceObject();
TargetObject targetObject = new TargetObject();
Converter converter = new SpringCopyConverter();
BeanCopier beanCopier = BeanCopier.create(SourceObject.class, TargetObject.class, true);
beanCopier.copy(sourceObject, targetObject, converter);

經過循環復制測試(源對象與目標對象各160個屬性):

  • 第一種:Java反射通過判斷屬性類型,常用類型的屬性值都能復制,但是不優化的前提下效率最慢;
  • 第二種:屬性類型不同時無法復制,且效率相對較慢;
  • 第三種:耗時最少,不使用轉換器時,屬性類型不同時無法復制,使用轉換器後,耗時會相對變長;
  • 第四種:與第三種相似,但是耗時相對較長;

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: