对象克隆

来源:互联网 发布:微信扫码抽奖软件 编辑:程序博客网 时间:2024/05/17 18:28
package com.point.gameCompanion.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import com.point.gameCompanion.entity.AnswerUser;
import com.point.gameCompanion.entity.GameAnswer;
import com.point.gameCompanion.entity.UserInfo;

public class ConverObjectParam {
    /**
     * 反射注入 用户信息 不够灵活  试验了一下
     * @param objS
     */
    public static <T> void SetUserInfo(List<T> objS){
        Class<?> clazz = null;
        Method methodPhotoUrl = null;
        Method methodUserName = null;
        for (T gameAnswer : objS) {
            try {
                if(null == clazz){
                    clazz = gameAnswer.getClass();
                    methodUserName = clazz.getMethod("setUserName",String.class);//创建用户 get  set  方法模型
                    methodPhotoUrl = clazz.getMethod("setHeadUrl", String.class);
                }
                UserInfo user = Robot.creartUser( null, null,Robot.GET_ROBOT_USER_TEXT);//获得一个用户的信息
                methodPhotoUrl.invoke(gameAnswer, user.getHeadUrl());//注入用户属性
                methodUserName.invoke(gameAnswer,user.getUserName());
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    /**   用户相同属性名称的值克隆  结合上面方法  反射机制应用      toObj 设值对象。objSource源对象

    */

    public static void toObject(Object toObj,Object objSource){
        Class<?> toObjClazz = toObj.getClass();
        Class<?> objSourceClazz = objSource.getClass();
        
        Field toObjFields[] = toObjClazz.getDeclaredFields();
        Field objSourceFields[] = objSourceClazz.getDeclaredFields();
        
        String[]   objName   =   new   String[objSourceFields.length];
        Object[]   objValue   =   new   Object[objSourceFields.length];

        try{
            Field.setAccessible(objSourceFields,   true);
            for   (int   i   =   0;   i   <   objName.length;   i++)   {
                objName[i]   =   objSourceFields[i].getName();
               objValue[i]   =   objSourceFields[i].get(objSource);
            }
            
            Field.setAccessible(toObjFields,   true);
            for   (int   i   =   0;   i   <   toObjFields.length;   i++)   {
                String param = toObjFields[i].getName();
                for (int j = 0; j < objName.length; j++) {
                    if(objName[j] .equals(param) ){//属性名相同 进行赋值操作。   类型判断  以及排除操作没有考虑在内
                        param = param.substring(0, 1).toUpperCase() + param.substring(1);
                        //System.out.println(objName[i] + ":" + param);
                        // 拼接setter  以及get方法
                        String setMethodName = "set"+ param;
                        Method toObjMethod = toObjClazz.getMethod(setMethodName,toObjFields[i].getType());

                        String getMethodName = "get"+ param;
                        Method objSourceMethod = objSourceClazz.getMethod(getMethodName);
                        Object value = objSourceMethod.invoke(objSource);
                        
                        // 赋值
                        try {
                            toObjMethod.invoke(toObj, value);
                        } catch (Exception e) {
                            System.out.println("Error! 属性 : 【 " + param + " 】, 值:【"+ value +"】 值类型不匹配,无法赋值!");
                            System.out.println(objSource.getClass() +" 值类型 :"+ value.getClass());
                            System.out.println(toObj.getClass() +" 需要值类型 :"+ toObjFields[i].getType());
                            System.out.println("============================================================= ");
                        }
                    }
                }
            }
          
        } catch(Exception   e){
         e.printStackTrace();
        }
        
        
    }
    
    public <T> void name(T gameAnswer) {
        Class<?> clazz = gameAnswer.getClass();
        Method method;
        try {
            method = clazz.getMethod("setPhotoUrl", String.class);
        method.invoke(gameAnswer, "https://b-ssl.duitang.com/uploads/item/201409/18/20140918231127_LZQjr.png");
        
        method = clazz.getMethod("setUserName",String.class);
        method.invoke(gameAnswer,"都是这个名字");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    public static void main(String[] args) {
//        Pa pb= new Pa();
//        Pb pa= new Pb();
//        pa.setName("nihao");
//        pa.setAge(1);
//        pa.setH(0.0);
//        pa.setCc(0);
//        toObject(pb, pa);
//        System.out.println(pb.getName());
//        System.out.println(pb.getAge());
//        System.out.println(pb.getA());
//        System.out.println(pb. getCc());
        
        ConverObjectParam s= new ConverObjectParam();
        GameAnswer userInfo = new GameAnswer();
        s.name(userInfo);
        System.out.println(userInfo.getPhotoUrl());
        
        ConverObjectParam a = new ConverObjectParam();
        AnswerUser an = new AnswerUser();
        a.name(an);
        System.out.println(an.getUserName());
    }
}