Java 对象拷贝复制,对象属性拷贝复制

2024-08-30 19:28
文章标签 java 对象 属性 复制 拷贝

本文主要是介绍Java 对象拷贝复制,对象属性拷贝复制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • 前言
  • 一、假设有Student、People类如下
  • 二、方式一,使用modelmapper
    • 1.依赖
    • 2.工具类
    • 3. 测试
      • (1)student 与 people 的转换
      • (2)List\<student\> 与 List\<people\> 的转换
  • 二、方式二,使用 Spring 的 BeanUtils
    • 1.依赖
    • 2.工具类
    • 3. 测试
      • (1)student 与 people 的转换
      • (2)List\<student\> 与 List\<people\> 的转换

前言

之前写了一篇文章 java浅拷贝与深拷贝讲了如何深拷贝对象。

本文讲解如何通过第三方库来拷贝复制对象的属性值。

一、假设有Student、People类如下

public class Student {private int id;private String name;private int score;public Student() {}public Student(int id, String name, int score) {this.name = name;this.id = id;this.score = score;}//省略get、set方法
}
public class People {private int id;private String name;private int score;private int age;private String address;private String teacher;public People() {}public People(int id, String name, int score, int age, String address, String teacher) {this.id = id;this.name = name;this.score = score;this.age = age;this.address = address;this.teacher = teacher;}//省略get、set方法
}

二、方式一,使用modelmapper

1.依赖

        <dependency><groupId>org.modelmapper</groupId><artifactId>modelmapper</artifactId><version>3.2.1</version></dependency>

2.工具类

import org.modelmapper.ModelMapper;
import java.util.ArrayList;
import java.util.List;public class ConvertUtil {private static final ModelMapper MODEL_MAPPER = new ModelMapper();/*** 将源对象转换为目标类型对象。** @param source 源对象* @param targetClass 目标类型的 Class 对象* @param <S> 源对象的类型* @param <T> 目标对象的类型* @return 转换后的目标类型对象*/public static <S, T> T convert(S source, Class<T> targetClass) {return MODEL_MAPPER.map(source, targetClass);}/*** 克隆列表并将列表中的每个元素转换为目标类型。** @param sourceList 源列表* @param targetClass 目标类型的 Class 对象* @param <S> 源列表中元素的类型* @param <T> 目标列表中元素的类型* @return 转换后的目标类型列表*/public static <S, T> List<T> cloneList(List<S> sourceList, Class<T> targetClass) {List<T> targetList = new ArrayList<>();for (S source : sourceList) {T target = MODEL_MAPPER.map(source, targetClass);targetList.add(target);}return targetList;}
}

3. 测试

(1)student 与 people 的转换

		Student student = new Student(1, "张三", 98);//student转为peoplePeople people = ConvertUtil.convert(student, People.class);//输出System.out.println(people.getId());System.out.println(people.getName());System.out.println(people.getScore());System.out.println(people.getAddress());System.out.println(people.getTeacher());System.out.println("--------------------");People people1 = new People(2, "王五", 90, 28,"北京一中","王鹏");//people转为studentStudent student1 = ConvertUtil.convert(people1, Student.class);//输出System.out.println(student1.getId());System.out.println(student1.getName());System.out.println(student1.getScore());

输出的结果:

1
张三
98
null
null
--------------------
2
王五
90

(2)List<student> 与 List<people> 的转换

        Student student1 = new Student(1, "张三", 98);Student student2 = new Student(2, "李四", 95);List<Student> studentList1 = new ArrayList<>();studentList1.add(student1);studentList1.add(student2);//List<Student> 转为 List<People>List<People> peopleList1 = ConvertUtil.cloneList(studentList1, People.class);//输出peopleList1.forEach(people -> {System.out.println(people.getId());System.out.println(people.getName());System.out.println(people.getScore());System.out.println(people.getAddress());System.out.println(people.getTeacher());});System.out.println("--------------------");People people1 = new People(3, "王五", 91, 27, "北京一中", "王鹏");People people2 = new People(3, "赵二", 92, 28, "北京二中", "李梅");List<People> peopleList2 = new ArrayList<>();peopleList2.add(people1);peopleList2.add(people2);//List<People> 转为 List<Student>List<Student> studentList2 = ConvertUtil.cloneList(peopleList2, Student.class);//输出studentList2.forEach(student -> {System.out.println(student.getId());System.out.println(student.getName());System.out.println(student.getScore());});

输出的结果:

1
张三
98
null
null
2
李四
95
null
null
--------------------
3
王五
91
3
赵二
92

二、方式二,使用 Spring 的 BeanUtils

1.依赖

如果你的项目不是springboot,则需要添加如下依赖,springboot项目则不需要。

        <dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>5.3.39</version></dependency>

2.工具类

import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;public class ConvertUtil {/*** 将一个对象转换为目标类型的对象** @param source      源对象* @param targetClass 目标类* @param <T>         目标类型* @return 转换后的目标对象*/public static <T> T convert(Object source, Class<T> targetClass) {if (source == null) {return null;}try {T target = targetClass.getDeclaredConstructor().newInstance();BeanUtils.copyProperties(source, target);return target;} catch (ReflectiveOperationException e) {throw new RuntimeException("转化对象失败", e);}}/*** 克隆一个列表,并将列表中的每个元素转换为目标类型的对象** @param sourceList  源列表* @param targetClass 目标类* @param <S>         源类型* @param <T>         目标类型* @return 克隆后的列表*/public static <S, T> List<T> cloneList(List<S> sourceList, Class<T> targetClass) {if (sourceList == null) {return null;}List<T> targetList = new ArrayList<>();for (S source : sourceList) {T target = convert(source, targetClass);targetList.add(target);}return targetList;}
}

3. 测试

(1)student 与 people 的转换

		Student student = new Student(1, "张三", 98);//student转为peoplePeople people = ConvertUtil.convert(student, People.class);//输出System.out.println(people.getId());System.out.println(people.getName());System.out.println(people.getScore());System.out.println(people.getAddress());System.out.println(people.getTeacher());System.out.println("--------------------");People people1 = new People(2, "王五", 90, 28,"北京一中","王鹏");//people转为studentStudent student1 = ConvertUtil.convert(people1, Student.class);//输出System.out.println(student1.getId());System.out.println(student1.getName());System.out.println(student1.getScore());

输出的结果:

1
张三
98
null
null
--------------------
2
王五
90

(2)List<student> 与 List<people> 的转换

        Student student1 = new Student(1, "张三", 98);Student student2 = new Student(2, "李四", 95);List<Student> studentList1 = new ArrayList<>();studentList1.add(student1);studentList1.add(student2);//List<Student> 转为 List<People>List<People> peopleList1 = ConvertUtil.cloneList(studentList1, People.class);//输出peopleList1.forEach(people -> {System.out.println(people.getId());System.out.println(people.getName());System.out.println(people.getScore());System.out.println(people.getAddress());System.out.println(people.getTeacher());});System.out.println("--------------------");People people1 = new People(3, "王五", 91, 27, "北京一中", "王鹏");People people2 = new People(3, "赵二", 92, 28, "北京二中", "李梅");List<People> peopleList2 = new ArrayList<>();peopleList2.add(people1);peopleList2.add(people2);//List<People> 转为 List<Student>List<Student> studentList2 = ConvertUtil.cloneList(peopleList2, Student.class);//输出studentList2.forEach(student -> {System.out.println(student.getId());System.out.println(student.getName());System.out.println(student.getScore());});

输出的结果:

1
张三
98
null
null
2
李四
95
null
null
--------------------
3
王五
91
3
赵二
92

这篇关于Java 对象拷贝复制,对象属性拷贝复制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1121725

相关文章

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏

javacv依赖太大导致jar包也大的解决办法

《javacv依赖太大导致jar包也大的解决办法》随着项目的复杂度和依赖关系的增加,打包后的JAR包可能会变得很大,:本文主要介绍javacv依赖太大导致jar包也大的解决办法,文中通过代码介绍的... 目录前言1.检查依赖2.更改依赖3.检查副依赖总结 前言最近在写项目时,用到了Javacv里的获取视频

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima

SpringBoot全局域名替换的实现

《SpringBoot全局域名替换的实现》本文主要介绍了SpringBoot全局域名替换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录 项目结构⚙️ 配置文件application.yml️ 配置类AppProperties.Ja

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC