溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java怎么復(fù)制非空對象屬性值

發(fā)布時間:2021-09-01 14:43:47 來源:億速云 閱讀:310 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下java怎么復(fù)制非空對象屬性值,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

java 復(fù)制非空對象屬性值

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

用于對象拷貝,spring 和 Apache都提供了相應(yīng)的工具類方法,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 zhengmingliang911@gmail.com
     * @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 zhengmingliang911@gmail.com
     * @Time 2017年2月14日 下午5:15:30
     * @Description <p> 拷貝非空對象屬性值 </P>
     * @param source 源對象
     * @param target 目標(biāo)對象
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

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

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

@DynamicInsert(true)
@DynamicUpdate(true)

如果想對該注解進(jìn)一步了解的話,那么可以去官網(wǎng)看英文文檔,文檔解釋的很清楚,在此不再贅述了

java對象屬性復(fù)制的幾種方式

1.使用java反射機制

獲取對象的屬性和get、set方法進(jìn)行復(fù)制;

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);--第三個參數(shù)表示是否使用轉(zhuǎn)換器,false表示不使用,true表示使用
Converter converter = new CopyConverter();--自定義轉(zhuǎn)換器
beanCopier.copy(sourceObject, targetObject, converter);

轉(zhuǎn)換器(當(dāng)源對象屬性類型與目標(biāo)對象屬性類型不一致時,使用轉(zhuǎn)換器):

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);

經(jīng)過循環(huán)復(fù)制測試(源對象與目標(biāo)對象各160個屬性):

java怎么復(fù)制非空對象屬性值

  • 第一種:Java反射通過判斷屬性類型,常用類型的屬性值都能復(fù)制,但是不優(yōu)化的前提下效率最慢;

  • 第二種:屬性類型不同時無法復(fù)制,且效率相對較慢;

  • 第三種:耗時最少,不使用轉(zhuǎn)換器時,屬性類型不同時無法復(fù)制,使用轉(zhuǎn)換器后,耗時會相對變長;

  • 第四種:與第三種相似,但是耗時相對較長;

看完了這篇文章,相信你對“java怎么復(fù)制非空對象屬性值”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI