1. 程式人生 > >利用反射實現類的複製

利用反射實現類的複製

利用反射實現類的複製

筆者年前在專案中遇到資料複製報錯,根據排查,最終鎖定問題出在類的複製上面。經過多種嘗試,仍不行,遂放棄common.lang包中的辦法,利用反射寫個類複製的工具類。閒話不多說,直接上程式碼。

package com.xq.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
 * 類的拷貝
 * @author wangweiqiang
 *
*/
public class BeanProperties {

    public static void copy(Object target, Object source) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{


        Class sourceClass = source.getClass();
        Class targetClass = target.getClass();

        //獲取類的所有屬性
        Field[] sourceFields = sourceClass.getDeclaredFields();
        Field[] targetFields = targetClass.getDeclaredFields();

        //雙重迴圈 複製
        for (Field sourceField : sourceFields) {

            String sourceFieldName = sourceField.getName();
            Class sourceFieldType = sourceField.getType();

            //拼寫get方法名
            String methodName = sourceFieldName.substring(0, 1).toUpperCase()+sourceFieldName.substring(1);

            Method getMethod = sourceClass.getMethod("get"+methodName);
            //反射獲取屬性值
            Object value = getMethod.invoke(source);

             for (Field field : targetFields) {
                String targetFieldname = field.getName();

                //判斷目標屬性的名字和型別 是否一致
                if(targetFieldname.equals(sourceFieldName) && sourceFieldType.equals(field.getType())){
                 Method setMethod = targetClass.getMethod("set"+methodName, sourceFieldType);
                //invoke 執行set方法
                 setMethod.invoke(target, value);
                }
            }

        }

    }
}

測試類

package com.xq.test;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import com.xq.entity.UserSource;
import com.xq.entity.UserTarget;
import com.xq.util.BeanProperties;
/**
* 測試類
* @author Administrator
*
*/
public class BeanCopyDemo {

public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    UserTarget target = new UserTarget();
    UserSource source = new UserSource();

    source.setAddress("水電費水電費");
    source.setAge(18);
    source.setBirth(new Date());
    source.setUserName("測試反射");
    BeanProperties.copy(target, source);
    System.out.println("name:"+target.getUserName());
    System.out.println("sex:"+target.getSex());
    System.out.println("birth:"+target.getBirth());
    System.out.println("address:"+target.getAddress());
    }
}

下面貼一下實體類

package com.xq.entity;

import java.util.Date;
public class UserTarget {   
    private String userName;        
    private String address;     
    private String sex;     
    private Date birth; 

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }


    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}

測試結果:

name:測試反射
sex:null
birth:Sat Jan 07 00:31:06 CST 2017
address:水電費水電費

在此感謝一位朋友,因為你的支援,以後我會堅持更新部落格。