利用Java反射機制實現對象相同字段的複製

一、如何實現不同類型對象之間的複製問題?

1、爲什麼會有這個問題?

近來在進行一個項目開發的時候,爲了隱藏後端數據庫表結構、同時也爲了配合給前端一個更友好的API接口文檔(swagger API文檔),我採用POJO來對應數據表結構,使用VO來給傳遞前端要展示的數據,同時使用DTO來進行請求參數的封裝。以上是一個具體的場景,可以發現這樣子一個現象:POJO、VO、DTO對象是同一個數據的不同視圖,所以會有很多相同的字段,由於不同的地方使用不同的對象,無可避免的會存在對象之間的值遷移問題,遷移的一個特徵就是需要遷移的值字段相同。字段相同,於是纔有了不同對象之間進行值遷移複製的問題。

2、現有的解決方法

  1. 一個一個的get出來後又set進去。這個方法無可避免會增加很多的編碼複雜度,還是一些很沒有營養的代碼,看多了還會煩,所以作爲一個有點小追求的程序員都沒有辦法忍受這種摧殘。
  2. 使用別人已經存在的工具。在spring包裏面有一個可以複製對象屬性的工具方法,可以進行對象值的複製,下一段我們詳細去分析它的這個工具方法。
  3. 自己動手豐衣足食。自己造工具來用,之所以自己造工具不是因爲喜歡造工具,而是現有的工具沒辦法解決自己的需求,不得已而爲之。

二、他山之石可以攻玉,詳談spring的對象複製工具

1、看看spring的對象複製工具到底咋樣?

  1. 類名:org.springframework.beans.BeanUtils
  2. 這個類裏面所有的屬性複製的方法都調用了同一個方法,我們就直接分析這個原始的方法就行了。
    /**
	 * 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:這個類對象是target的父類或其實現的接口,用於控制屬性複製的範圍
	 * @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 {

		//這裏在校驗要複製的對象是不可以爲null的,這兩個方法可是會報錯的!!
		Assert.notNull(source, "Source must not be null");
		Assert.notNull(target, "Target must not be null");
		//這裏和下面的代碼就有意思了
		Class<?> actualEditable = target.getClass();//獲取目標對象的動態類型
		//下面判斷的意圖在於控制屬性複製的範圍
		if (editable != null) {
			//必須是target對象的父類或者其實現的接口類型,相當於instanceof運算符
			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);
						}
					}
				}
			}
		}
	}

2、對複製工具的一些看法和總結

總結上一段代碼的分析,我們發現spring自帶的工具有以下特點:

  1. 它名副其實的是在複製屬性,而不是字段!!
  2. 它可以通過一個目標對象的父類或者其實現的接口來控制需要複製屬性的範圍
  3. 很貼心的可以忽略原對象的某些字段,可以通過2的方法忽略某些目標對象的字段

但是,這遠遠不夠!!!我需要如下的功能:

  1. 複製對象的字段,而不是屬性,也就是說我需要一個更暴力的複製工具。
  2. 我需要忽略原對象的某些字段,同時也能夠忽略目標對象的某些字段。
  3. 我的項目還需要忽略原對象爲null的字段和目標對象不爲null的字段

帶着這三個需求,開始我的工具製造。

三、自己動手豐衣足食

1、我需要解析字節碼

爲了避免對字節碼的重複解析,使用緩存來保留解析過的字節碼解析結果,同時爲了不讓這個工具太佔用內存,使用軟引用來進行緩存,上代碼:

    /*
     ******************************************************
     * 基礎的用於支持反射解析的解析結果緩存,使用軟引用實現
     ******************************************************
     */
    private static final Map<Class<?>,SoftReference<Map<String,Field>>> resolvedClassCache = new ConcurrentHashMap<>();
    
    /**
     * 同步解析字節碼對象,將解析的結果放入到緩存 1、解析後的字段對象全部 accessAble
     * 1、返回的集合不支持修改,要修改請記得自己重新建一個複製的副本
     * @param sourceClass:需要解析的字節碼對象
     */
    @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
    public static Map<String,Field> resolveClassFieldMap(final Class<?> sourceClass){

        SoftReference<Map<String,Field>> softReference = resolvedClassCache.get(sourceClass);

        //判斷是否已經被初始化
        if(softReference == null || softReference.get() == null){

            //對同一個字節碼對象的解析是同步的,但是不同字節碼對象的解析是併發的,因爲字節碼對象只有一個
            synchronized(sourceClass){

                softReference = resolvedClassCache.get(sourceClass);

                if(softReference == null || softReference.get() == null){

		            //採用:<字段名稱,字段對象> 來記錄解析結果
                    Map<String,Field> fieldMap = new HashMap<>();

                    /*
                    Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this
                    Class object. This includes public, protected, default access, and private fields, but excludes inherited fields
                    */
                    Field[] declaredFields = sourceClass.getDeclaredFields();

                    if(declaredFields != null && declaredFields.length > 0){

                        for(Field field : declaredFields){

                            /*
                            Set the accessible flag for this object to the indicated boolean value.
                            */
                            field.setAccessible(true);
							  //字段名稱和字段對象
                            fieldMap.put(field.getName(),field);
                        }
                    }

                    //設置爲不變Map,這個肯定是不能夠改的啊!所以取的時候需要重新構建一個map
                    fieldMap = Collections.unmodifiableMap(fieldMap);

                    softReference = new SoftReference<>(fieldMap);

                    /*
                    更新緩存,將解析後的數據加入到緩存裏面去
                     */
                    resolvedClassCache.put(sourceClass,softReference);

                    return fieldMap;
                }
            }
        }

        /*
        運行到這裏來的時候要麼早就存在,要麼就是已經被其他的線程給初始化了
         */
        return softReference.get();
    }

2、我需要能夠進行對象的複製,基本方法

    /**
     * 進行屬性的基本複製操作
     * @param source:源對象
     * @param sourceFieldMap:原對象解析結果
     * @param target:目標對象
     * @param targetFieldMap:目標對象解析結果
     */
    public static void copyObjectProperties(Object source,Map<String,Field> sourceFieldMap,Object target,Map<String,Field> targetFieldMap){

        //進行屬性值複製
        sourceFieldMap.forEach(
                (fieldName,sourceField) -> {

                    //查看目標對象是否存在這個字段
                    Field targetField = targetFieldMap.get(fieldName);

                    if(targetField != null){

                        try{
                            //對目標字段進行賦值操作
                            targetField.set(target,sourceField.get(source));
                        }catch(IllegalAccessException e){
                            e.printStackTrace();
                        }
                    }
                }
        );
    }

3、夜深了,準備睡覺了

基於這兩個方法,對其進行封裝,實現了我需要的功能,並且在項目中運行目前還沒有bug,應該可以直接用在生產環境,各位看官覺得可以可以拿來試一試哦!!

4、完整的代碼(帶註釋:需要自取,無外部依賴,拿來即用)

package edu.cqupt.demonstration.common.util;

import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 反射的工具集,主要用於對對象的複製操作
 */
public class ReflectUtil {

    /*
     ******************************************************
     * 基礎的用於支持反射解析的解析結果緩存,使用軟引用實現
     ******************************************************
     */
    private static final Map<Class<?>,SoftReference<Map<String,Field>>> resolvedClassCache = new ConcurrentHashMap<>();

    /*
     ****************************************
     * 獲取一個對象指定條件字段名稱的工具方法
     ****************************************
     */

    /**
     * 獲取一個對象裏面字段爲null的字段名稱集合
     */
    public static String[] getNullValueFieldNames(Object source){

        //非空校驗:NullPointerException
        Objects.requireNonNull(source);

        Class<?> sourceClass = source.getClass();

        //從緩存裏面獲取,如果緩存裏面沒有就會進行第一次反射解析
        Map<String,Field> classFieldMap = getClassFieldMapWithCache(sourceClass);

        List<String> nullValueFieldNames = new ArrayList<>();

        classFieldMap.forEach(
                (fieldName,field) -> {

                    try{
                        //挑選出值爲null的字段名稱
                        if(field.get(source) == null){
                            nullValueFieldNames.add(fieldName);
                        }
                    }catch(IllegalAccessException e){
                        e.printStackTrace();
                    }
                }
        );

        return nullValueFieldNames.toArray(new String[]{});
    }

    /**
     * 獲取一個對象裏面字段不爲null的字段名稱集合
     */
    public static String[] getNonNullValueFieldNames(Object source){

         //非空校驗
        Objects.requireNonNull(source);

        //獲取空值字段名稱
        String[] nullValueFieldNames = getNullValueFieldNames(source);

        Map<String,Field> classFieldMap = getClassFieldMapWithCache(source.getClass());

        //獲取全部的字段名稱,因爲原數據沒辦法修改,所以需要重新建立一個集合來進行判斷
        Set<String> allFieldNames = new HashSet<>(classFieldMap.keySet());

        //移除掉值爲null的字段名稱
        allFieldNames.removeAll(Arrays.asList(nullValueFieldNames));

        return allFieldNames.toArray(new String[]{});
    }

    /*
     ***************************************************************
     * 複製一個對象的相關工具方法,注意事項如下:
     * 1、只能複製字段名稱相同且數據類型兼容的字段數據
     * 2、只能複製這個對象實際類(運行時動態類型)裏面聲明的各種字段
     ***************************************************************
     */

    /**
     * 將一個對象裏面字段相同、類型兼容的數據複製到另外一個對象去
     * 1、只複製類的運行時類型的聲明的全部訪問權限的字段
     * @param source:從這個對象複製
     * @param target:複製到這個對象來
     */
    public static void copyPropertiesSimple(Object source,Object target){

        copyObjectProperties(
                source,new HashMap<>(getClassFieldMapWithCache(source.getClass())),
                target,new HashMap<>(getClassFieldMapWithCache(target.getClass())));
    }

    /**
     * 除實現 copyPropertiesSimple 的功能外,會忽略掉原對象的指定字段的複製
     * @param ignoreFieldNames:需要忽略的原對象字段名稱集合
     */
    public static void copyPropertiesWithIgnoreSourceFields(Object source,Object target,String ...ignoreFieldNames){

        Map<String,Field> sourceFieldMap = new HashMap<>(getClassFieldMapWithCache(source.getClass()));

        filterByFieldName(sourceFieldMap,ignoreFieldNames);

        copyObjectProperties(source,sourceFieldMap,target,new HashMap<>(getClassFieldMapWithCache(target.getClass())));
    }

    /**
     * 除實現 copyPropertiesSimple 的功能外,會忽略掉原對象字段值爲null的字段
     */
    public static void copyPropertiesWithNonNullSourceFields(Object source,Object target){

        Map<String,Field> sourceFieldMap = new HashMap<>(getClassFieldMapWithCache(source.getClass()));

        filterByFieldValue(source,sourceFieldMap,true);

        copyObjectProperties(source,sourceFieldMap,target,new HashMap<>(getClassFieldMapWithCache(target.getClass())));
    }

    /**
     * 除實現 copyPropertiesSimple 的功能外,會忽略掉目標對象的指定字段的複製
     * @param ignoreFieldNames:需要忽略的原對象字段名稱集合
     */
    public static void copyPropertiesWithIgnoreTargetFields(Object source,Object target,String ...ignoreFieldNames){

        Map<String,Field> targetFieldMap = new HashMap<>(getClassFieldMapWithCache(target.getClass()));

        filterByFieldName(targetFieldMap,ignoreFieldNames);

        copyObjectProperties(source,new HashMap<>(getClassFieldMapWithCache(source.getClass())),target,targetFieldMap);
    }

    /**
     * 除實現 copyPropertiesSimple 的功能外,如果目標對象的屬性值不爲null將不進行覆蓋
     */
    public static void copyPropertiesWithTargetFieldNonOverwrite(Object source,Object target){

        Map<String,Field> targetFieldMap = new HashMap<>(getClassFieldMapWithCache(target.getClass()));

        filterByFieldValue(target,targetFieldMap,false);

        copyObjectProperties(source,new HashMap<>(getClassFieldMapWithCache(source.getClass())),target,targetFieldMap);
    }

    /**
     * 進行復制的完全定製複製
     * @param source:源對象
     * @param target:目標對象
     * @param ignoreSourceFieldNames:需要忽略的原對象字段名稱集合
     * @param ignoreTargetFieldNames:要忽略的目標對象字段集合
     * @param isSourceFieldValueNullAble:是否在源對象的字段爲null的時候仍然進行賦值
     * @param isTargetFiledValueOverwrite:是否在目標對象的值不爲null的時候仍然進行賦值
     */
    public static void copyPropertiesWithConditions(Object source,Object target
            ,String[] ignoreSourceFieldNames,String[] ignoreTargetFieldNames
            ,boolean isSourceFieldValueNullAble,boolean isTargetFiledValueOverwrite){

        Map<String,Field> sourceFieldMap = new HashMap<>(getClassFieldMapWithCache(source.getClass()));
        Map<String,Field> targetFieldMap = new HashMap<>(getClassFieldMapWithCache(target.getClass()));

        if(!isSourceFieldValueNullAble){

            filterByFieldValue(source,sourceFieldMap,true);
        }

        if(!isTargetFiledValueOverwrite){

            filterByFieldValue(target,targetFieldMap,false);
        }

        filterByFieldName(sourceFieldMap,ignoreSourceFieldNames);

        filterByFieldName(targetFieldMap,ignoreTargetFieldNames);

        copyObjectProperties(source,sourceFieldMap,target,targetFieldMap);
    }

    /*
     ******************************
     * 內部工具方法或者內部兼容方法
     ******************************
     */

    /**
     * 同步解析字節碼對象,將解析的結果放入到緩存 1、解析後的字段對象全部 accessAble
     * 1、返回的集合不支持修改,要修改請記得自己重新建一個複製的副本
     * @param sourceClass:需要解析的字節碼對象
     */
    @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
    public static Map<String,Field> resolveClassFieldMap(final Class<?> sourceClass){

        SoftReference<Map<String,Field>> softReference = resolvedClassCache.get(sourceClass);

        //判斷是否已經被初始化
        if(softReference == null || softReference.get() == null){

            //對同一個字節碼對象的解析是同步的,但是不同字節碼對象的解析是併發的
            synchronized(sourceClass){

                softReference = resolvedClassCache.get(sourceClass);

                if(softReference == null || softReference.get() == null){

                    Map<String,Field> fieldMap = new HashMap<>();

                    /*
                    Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this
                    Class object. This includes public, protected, default access, and private fields, but excludes inherited fields
                    */
                    Field[] declaredFields = sourceClass.getDeclaredFields();

                    if(declaredFields != null && declaredFields.length > 0){

                        for(Field field : declaredFields){

                            /*
                            Set the accessible flag for this object to the indicated boolean value.
                            */
                            field.setAccessible(true);

                            fieldMap.put(field.getName(),field);
                        }
                    }

                    //設置爲不變Map
                    fieldMap = Collections.unmodifiableMap(fieldMap);

                    softReference = new SoftReference<>(fieldMap);

                    /*
                    更新緩存,將解析後的數據加入到緩存裏面去
                     */
                    resolvedClassCache.put(sourceClass,softReference);

                    return fieldMap;
                }
            }
        }

        /*
        運行到這裏來的時候要麼早就存在,要麼就是已經被其他的線程給初始化了
         */
        return softReference.get();
    }

    /**
     * 確保正確的從緩存裏面獲取解析後的數據
     * 1、返回的集合不支持修改,要修改請記得自己重新建一個複製的副本
     * @param sourceClass:需要解析的字節碼對象
     */
    public static Map<String,Field> getClassFieldMapWithCache(Class<?> sourceClass){

        //查看緩存裏面有沒有已經解析完畢的現成的數據
        SoftReference<Map<String,Field>> softReference = resolvedClassCache.get(sourceClass);

        //確保classFieldMap的正確初始化和緩存
        if(softReference == null || softReference.get() == null){

            //解析字節碼對象
            return resolveClassFieldMap(sourceClass);
        }else {

            //從緩存裏面正確的取出數據
            return softReference.get();
        }
    }

    /**
     * 將一個可變參數集合轉換爲List集合,當爲空的時候返回空集合
     */
    public static <T> List<T> resolveArrayToList(T ...args){

        List<T> result = new ArrayList<>();

        if(args != null && args.length > 0){

            result = Arrays.asList(args);
        }

        return result;
    }

    /**
     * 進行屬性的基本複製操作
     * @param source:源對象
     * @param sourceFieldMap:原對象解析結果
     * @param target:目標對象
     * @param targetFieldMap:目標對象解析結果
     */
    public static void copyObjectProperties(Object source,Map<String,Field> sourceFieldMap,Object target,Map<String,Field> targetFieldMap){

        //進行屬性值複製
        sourceFieldMap.forEach(
                (fieldName,sourceField) -> {

                    //查看目標對象是否存在這個字段
                    Field targetField = targetFieldMap.get(fieldName);

                    if(targetField != null){

                        try{
                            //對目標字段進行賦值操作
                            targetField.set(target,sourceField.get(source));
                        }catch(IllegalAccessException e){
                            e.printStackTrace();
                        }
                    }
                }
        );
    }

    /**
     * 忽略掉對象裏面的某些字段
     */
    public static void filterByFieldName(Map<String,Field> fieldMap,String ... ignoreFieldNames){

        //需要忽略的對象字段
        List<String> ignoreNames = ReflectUtil.<String>resolveArrayToList(ignoreFieldNames);

        //移除忽略的對象字段
        fieldMap.keySet().removeAll(ignoreNames);
    }

    /**
     * 忽略掉非空的字段或者空的字段
     */
    public static void filterByFieldValue(Object object,Map<String,Field> fieldMap,boolean filterNullAble){

        Iterator<String> iterator = fieldMap.keySet().iterator();

        if(filterNullAble){

            while(iterator.hasNext()){

                try{
                    //移除值爲null的字段
                    if(fieldMap.get(iterator.next()).get(object) == null){
                        iterator.remove();
                    }
                }catch(IllegalAccessException e){
                    e.printStackTrace();
                }
            }
        }else {

            while(iterator.hasNext()){

                try{
                    //移除字段不爲null的字段
                    if(fieldMap.get(iterator.next()).get(object) != null){
                        iterator.remove();
                    }
                }catch(IllegalAccessException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章