package com.bcxin.ins.utils;

import com.bcxin.ins.entity.policy_core.InsInsuranceSlip;
import com.bcxin.ins.supply.business.entity.InsureOrderView;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 拷贝工具类
 *
 */
public class CopyUtil {
    /**
     *
     * @param so 对象源
     * @param target 目标对象
     * @param <S>
     * @param <T>
     * @throws IllegalAccessException
     */
    public static <S, T extends S> T copy(S so, T target) throws IllegalAccessException {
        try {
            if (so == null||so.getClass() == null) {
                return null;
            }
            Field[] getters = so.getClass().getDeclaredFields();
            Field[] setters = target.getClass().getSuperclass().getDeclaredFields();
            Field getField=null;
            Field setField=null;
            for (int j = 0; j < getters.length; j++) {
                getField = getters[j];
                for (int i = 0; i < setters.length; i++) {
                    setField = setters[i];
                    if (setField.getName().compareTo(getField.getName()) == 0) {
                        //获取get方法名
                        String methodName = "get"+getField.getName().substring(0, 1).toUpperCase()
                                +getField.getName().replaceFirst("\\w", "");
                        Method getMethod = so.getClass().getDeclaredMethod(methodName);
                        //打破封装
                        getMethod.setAccessible(true);
                        //得到该方法的值
                        Object methodValue = getMethod.invoke(so);
                        //判断值是否为空或者为null,非的话这过滤前后空格
                        if(methodValue != null && !"".equals(methodValue)){
                            //获取set方法名
                            String setMethodName = "set"+setField.getName().substring(0, 1).toUpperCase()
                                    +setField.getName().replaceFirst("\\w", "");
                            //得到get方法的Method对象,带参数
                            Method setMethod = target.getClass().getSuperclass().getDeclaredMethod(setMethodName,setField.getType());
                            setMethod.setAccessible(true);
                            //赋值
                            setMethod.invoke(target, methodValue);
                        }
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return target;
    }

    public static void main(String [] args){
        InsInsuranceSlip insInsuranceSlip = new InsInsuranceSlip();
        insInsuranceSlip.setIns_insurance_slip_id(111L);
        try{
            InsureOrderView orderView=CopyUtil.copy(insInsuranceSlip,new InsureOrderView());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}