A类中的某些属性在B类中存在,把相同的属性从A类复制到B类的工具类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/***
 * A类中的某些属性在B类中存在,把相同的属性从A类复制到B类
 */
public class AttributeTransferUtil {

    private static Logger logger = LoggerFactory.getLogger(AttributeTransferUtil.class);

    public static Object cloneAttribute(Object clone, Object beCloned){
        Field[] fieldClone = null;
        Field[] fieldBeCloned = null;
        Map<String, Field> map  = new HashMap<String, Field>();
        try {
            Class<?> classClone = clone.getClass();
            Class<?> classBecloned = beCloned.getClass();
            fieldClone = classClone.getDeclaredFields();
            fieldBeCloned = classBecloned.getDeclaredFields();

            for (int i = 0; i < fieldBeCloned.length; i++) {
                map.put(fieldBeCloned[i].getName(), fieldBeCloned[i]);
            }

            for (int j = 0; j < fieldClone.length; j++) {
                String fieldCloneName = fieldClone[j].getName();
                Field field = map.get(fieldCloneName);
                if (field != null) {
                    Method getMethod = classClone.getMethod(getMethodName(fieldCloneName));
                    Method setMethod = classBecloned.getMethod(setMethodName(fieldCloneName), field.getType());
                    setMethod.invoke(beCloned, getMethod.invoke(clone));
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            fieldClone = null;
            fieldBeCloned = null;
            map.clear();
        }
        return beCloned;
    }

    private static String getMethodName(String fieldName){
        String head = fieldName.substring(0, 1).toUpperCase();
        String tail = fieldName.substring(1);
        return "get" + head + tail;
    }

    private static String setMethodName(String fieldName){
        String head = fieldName.substring(0, 1).toUpperCase();
        String tail = fieldName.substring(1);
        return "set" + head + tail;
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值