zoukankan      html  css  js  c++  java
  • 利用反射实现类的复制

    利用反射实现类的复制

    笔者年前在项目中遇到数据复制报错,根据排查,最终锁定问题出在类的复制上面。经过多种尝试,仍不行,遂放弃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:水电费水电费
    

    在此感谢一位朋友,因为你的支持,以后我会坚持更新博客。

  • 相关阅读:
    vue doubleclick 鼠标双击事件
    我是如何通过CSRF拿到Shell的
    js生成一个不重复的ID的函数的进化之路
    浅谈企业内部安全漏洞的运营(一):规范化
    如何让微信丢骰子永远只出“666”
    全能无线渗透测试工具,一个LAZY就搞定了
    关于8月31日维基解密被攻击的观察与分析
    VS2013 单元测试(使用VS2013自带的单元测试)
    解决WCF部署到IIS出现“证书必须具有能够进行密钥交换的私钥,该进程必须具有访问私钥的权限”
    VS2013 MVC Web项目使用内置的IISExpress支持局域网内部机器(手机、PC)访问、调试
  • 原文地址:https://www.cnblogs.com/lanxuan826/p/9873697.html
Copyright © 2011-2022 走看看