java如何用反射将一个对象复制给另一个对象

 更新时间:2023年09月25日 09:16:29   作者:YoungMirror  
这篇文章主要介绍了java如何用反射将一个对象复制给另一个对象问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

java用反射将一个对象复制给另一个对象

@SneakyThrows
    public static Object objectClone(Object newObject,Object oldObject){
        Field[] oldFields = oldObject.getClass().getDeclaredFields();
        Field newField;
        for (Field oldField : oldFields){
            oldField.setAccessible(true);
            newField = newObject.getClass().getDeclaredField(oldField.getName());
            newField.setAccessible(true);
            newField.set(newObject,oldField.get(oldObject));
        }
        return newObject;
    }

java复制一个对象使新对象和源对象值相同,地址不同

1. 实体(3个 模拟多层父级)支持多层父级和List,map的copy值

public class StudentDemo extends StudentF {
    private Integer stuId;
    private String stuName;
    private String stuPrice;
    private boolean flg;
    private List<String> listString;
    private HashMap<String, StuType> mapType;
    public HashMap<String, StuType> getMapType() {
        return mapType;
    }
    public void setMapType(HashMap<String, StuType> mapType) {
        this.mapType = mapType;
    }
    public List<String> getListString() {
        return listString;
    }
    public void setListString(List<String> listString) {
        this.listString = listString;
    }
    public boolean isFlg() {
        return flg;
    }
    public void setFlg(boolean flg) {
        this.flg = flg;
    }
    public StudentDemo(HashMap<String, StuType> mapType, List<StuType> listType, List<String> listString, Integer stuId, String stuName, String stuPrice, String stuSex, Integer stuAge, String stuNum, String stuTel, boolean isFlg) {
        this.stuId = stuId;
        this.stuName = stuName;
        this.stuPrice = stuPrice;
        super.setStudentSex(stuSex);
        super.setStudentAge(stuAge);
        super.setStuNum(stuNum);
        super.setTel(stuTel);
        this.flg = isFlg;
        this.listString = listString;
        super.setListType(listType);
        this.mapType = mapType;
    }
    public StudentDemo(){}
    @Override
    public String toString() {
        return "StudentDemo{" +
                "stuId=" + stuId +
                ", stuName='" + stuName + '\'' +
                ", stuPrice='" + stuPrice + '\'' +
                ", stuSex='" + super.getStudentSex() + '\'' +
                ", stuAge='" + super.getStudentAge() + '\'' +
                ", stuNum='" + super.getStuNum() + '\'' +
                ", stuTel='" + super.getTel() + '\'' +
                ", flg='" + flg + '\'' +
                ", listString='" + listString + '\'' +
                ", listType='" + super.getListType() + '\'' +
                ", mapType='" + mapType + '\'' +
                '}';
    }
    public Integer getStuId() {
        return stuId;
    }
    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public String getStuPrice() {
        return stuPrice;
    }
    public void setStuPrice(String stuPrice) {
        this.stuPrice = stuPrice;
    }
}
public class StudentF extends StudentX {
    private String studentSex;
    private Integer studentAge;
    private List<StuType> listType;
    public List<StuType> getListType() {
        return listType;
    }
    public void setListType(List<StuType> listType) {
        this.listType = listType;
    }
    public String getStudentSex() {
        return studentSex;
    }
    public void setStudentSex(String studentSex) {
        this.studentSex = studentSex;
    }
    public Integer getStudentAge() {
        return studentAge;
    }
    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }
}
public class StudentX {
    private String stuNum;
    private String Tel;
    public String getStuNum() {
        return stuNum;
    }
    public void setStuNum(String stuNum) {
        this.stuNum = stuNum;
    }
    public String getTel() {
        return Tel;
    }
    public void setTel(String tel) {
        Tel = tel;
    }
}

2. 工具类

package com.books.utils;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
 *  复制一个实体对象
 *  修改新对象时不影响源对象的值
 * @param <T> 项目中任意类型
 */
public class CopyObjectEntity<T> {
	/**
     *  复制实体方法
     * @param orderEntity 源对象
     * @param newEntity 新对象
     * @return 新对象
     */
    public T newPojo(Object orderEntity, Object newEntity){
        // 新对象
        T newPojo = null;
        try {
            // 源对象
            T orderPojo = (T)orderEntity;
            newPojo = (T)newEntity;
            // 获取所有方法,包括父类
            Method[] orderObject = orderPojo.getClass().getMethods();
            // 遍历所有方法
            for(int a = 0; a < orderObject.length; a ++){
                // 得到每一个方法名称
                String name = orderObject[a].getName();
                // 判断获取需要的(普通的字段都是get/set),这里获取get方法因为get到值才能赋值
                if(!name.equals("setClass") && !name.equals("class") && !name.equals("getClass") && name.startsWith("get")){
                    // 获取方法
                    Method method = orderPojo.getClass().getMethod(name, new Class[] {});
                    // 执行方法
                    Object value = method.invoke(orderPojo, new Object[] {});
                    // 拼接set方法
                    String aa = orderObject[a].getName().substring(3);
                    String bb = aa.substring(0, 1).toUpperCase();
                    String setter = bb + aa.substring(1);
                    // 创建描述器
                    PropertyDescriptor pd = new PropertyDescriptor(setter, newPojo.getClass());
                    //为上面声明的字段设置set方法(又称内省)
                    Method setMethod = pd.getWriteMethod();
                    // 执行set
                    setMethod.invoke(newPojo, value);
                }
                // 判断是boolean的字段get时为is
                if(!name.equals("setClass") && !name.equals("class") && !name.equals("getClass") && name.startsWith("is")){
                    Method method = orderPojo.getClass().getMethod(name, new Class[] {});
                    Object value = method.invoke(orderPojo, new Object[] {});
                    String aa = orderObject[a].getName().substring(2);
                    String bb = aa.substring(0, 1).toUpperCase();
                    String setter = bb + aa.substring(1);
                    PropertyDescriptor pd = new PropertyDescriptor(setter, newPojo.getClass());
                    //为上面声明的字段设置set方法(又称内省)
                    Method setMethod = pd.getWriteMethod();
                    // 执行set
                    setMethod.invoke(newPojo, value);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return newPojo;
    }
}

3. 测试

    public void test7(){
        List<String> ls = new ArrayList<>();
        ls.add("aa");
        ls.add("bb");
        ls.add("cc");
        List<StuType> listType = new ArrayList<>();
        listType.add(new StuType(1, "类型1"));
        listType.add(new StuType(2, "类型2"));
        HashMap<String, StuType> mapType = new HashMap<>();
        mapType.put("11", new StuType(11, "map1"));
        mapType.put("22", new StuType(22, "map2"));
        StudentDemo studentDemo = new StudentDemo(mapType, listType, ls,1, "aa" ,null, "男", 23, "010010", "15244669988", true);
        StudentDemo studentDemo1 = new StudentDemo();
        new CopyObjectEntity<StudentDemo>().newPojo(studentDemo, studentDemo1);
        System.out.println("复制完的新对象"+studentDemo1);
        studentDemo1.setStuId(22);
        studentDemo1.setStuName("你好啊");
        studentDemo1.setStuPrice("啦啦啦");
        studentDemo1.setStudentSex("女");
        studentDemo1.setStudentAge(20);
        studentDemo1.setStuNum("没有学号");
        studentDemo1.setTel("没有电话");
        studentDemo1.setFlg(false);
        List<String> ls1 = new ArrayList<>();
        ls1.add("33");
        ls1.add("44");
        ls1.add("55");
        List<StuType> listType1 = new ArrayList<>();
        listType1.add(new StuType(-1, "类型-1"));
        listType1.add(new StuType(-2, "类型-2"));
        HashMap<String, StuType> mapType1 = new HashMap<>();
        mapType1.put("11", new StuType(-11, "map-1"));
        mapType1.put("22", new StuType(-22, "map-2"));
        studentDemo1.setListType(listType1);
        studentDemo1.setMapType(mapType1);
        studentDemo1.setListString(ls1);
        System.out.println("源对象"+studentDemo);
        System.out.println("修改复制后对象"+studentDemo1);
        System.out.println("再次查看源对象"+studentDemo);
    }

4. 结果

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • java修改JFrame默认字体方式

    java修改JFrame默认字体方式

    这篇文章主要介绍了java修改JFrame默认字体方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • SpringBoot整合Redis、ApachSolr和SpringSession的示例

    SpringBoot整合Redis、ApachSolr和SpringSession的示例

    本篇文章主要介绍了SpringBoot整合Redis、ApachSolr和SpringSession的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • JAVA8 十大新特性详解

    JAVA8 十大新特性详解

    本教程将Java8的新特新逐一列出,并将使用简单的代码示例来指导你如何使用默认接口方法,lambda表达式,方法引用以及多重Annotation,之后你将会学到最新的API上的改进,比如流,函数式接口,Map以及全新的日期API
    2014-03-03
  • spring-boot中的SPI机制实例讲解

    spring-boot中的SPI机制实例讲解

    这篇文章主要介绍了spring-boot中的SPI机制实例讲解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • 详解基于Spring Boot/Spring Session/Redis的分布式Session共享解决方案

    详解基于Spring Boot/Spring Session/Redis的分布式Session共享解决方案

    本篇文章主要介绍了详解基于Spring Boot/Spring Session/Redis的分布式Session共享解决方案 ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06
  • SpringBoot集成Sa-Token实现权限认证流程入门教程

    SpringBoot集成Sa-Token实现权限认证流程入门教程

    本文详解SpringBoot集成Sa-Token框架的入门步骤,涵盖依赖添加、配置设置、拦截器注册、权限角色逻辑定义、设备工具类创建及登录/注销功能改造,通过注解实现鉴权,解决权限认证问题,感兴趣的朋友跟随小编一起看看吧
    2025-09-09
  • Java使用XWPFDocument生成word文档的示例代码

    Java使用XWPFDocument生成word文档的示例代码

    XWPFDocument 是 Apache POI 库中用于操作 .docx 格式 Word 文档的核心类,本文将针对 XWPFDocument 进行详细解析,涵盖其核心功能、常见用法及实际开发中的关键点
    2025-12-12
  • SpringBoot中实现文件上传、下载、删除功能的步骤

    SpringBoot中实现文件上传、下载、删除功能的步骤

    本文将详细介绍如何在 Spring Boot 中实现文件上传、下载、删除功能,采用的技术框架包括:Spring Boot 2.4.2、Spring MVC、MyBatis 3.5.6、Druid 数据源、JUnit 5 等,文中有详细的操作步骤和示例代码供大家参考,需要的朋友可以参考下
    2024-01-01
  • 深入理解Mybatis一级缓存

    深入理解Mybatis一级缓存

    客户端向数据库服务器发送同样的sql查询语句,如果每次都去访问数据库,会导致性能的降低,那么怎么提高呢?下面小编给大家分享下mybatis为我们提供了一级缓存的策略
    2016-12-12
  • java多线程之wait(),notify(),notifyAll()的详解分析

    java多线程之wait(),notify(),notifyAll()的详解分析

    本篇文章是对java多线程 wait(),notify(),notifyAll()进行了详细的分析介绍,需要的朋友参考下
    2013-06-06

最新评论