欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 自定义Bean转换工具类

自定义Bean转换工具类

2024/10/24 4:47:52 来源:https://blog.csdn.net/shy_1762538422/article/details/140536351  浏览:    关键词:自定义Bean转换工具类

BeanConvertor工具类:简化Java对象转换的利器

在Java开发中,我们经常需要在不同的对象之间转换数据。这可能是因为我们需要将数据从一个层(如数据访问层)转移到另一个层(如服务层或表示层),或者是因为我们需要将外部API的数据结构转换为我们的内部数据结构。这种转换过程可能会变得繁琐且容易出错。为了解决这个问题,我们可以自定义一个强大的工具类:BeanConvertor。

BeanConvertor类的完整代码

首先,让我们看一下BeanConvertor类的完整代码:

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;/*** @desc: Bean转换工具类* @author: shy* @date: 2024/07/19 0:08*/
public class BeanConvertor {private static final ObjectMapper CONVERTOR_MAPPER = new ObjectMapper();/*** 将p1对象转换为 P2 类型的对象。* 基于反射,主要用于相同结构的对象间属性拷贝** @param fromObj     源对象* @param targetClazz 目标对象的类* @return p2 对象* @author shy* @date: 2024/07/19 0:08*/public static <P1, P2> P2 convertTo(P1 fromObj, Class<P2> targetClazz) {if (fromObj == null) {return null;}P2 targetObj;try {targetObj = targetClazz.newInstance();} catch (Exception e) {throw new IllegalArgumentException("Can not new object of class " + targetClazz.getName(), e);}BeanUtils.copyProperties(fromObj, targetObj);return targetObj;}/*** 将 源列表 中的对象拷贝到新目标类列表中。* 基于反射,主要用于相同结构的对象间属性拷贝** @param fromList    源列表* @param targetClazz 目标对象的泛型* @return 以目标类为元素类型的列表。* @author shy* @date: 2024/07/19 0:08*/public static <C1, C2> List<C2> convertListTo(List<C1> fromList, Class<C2> targetClazz) {if (fromList == null || fromList.isEmpty()) {return Collections.emptyList();}List<C2> targetList = new LinkedList<>();for (C1 fromObj : fromList) {targetList.add(convertTo(fromObj, targetClazz));}return targetList;}/*** 将p1对象转换为 P2 类型的对象。* 基于 JSON 序列化和反序列化,可以处理更复杂的类型转换* 例如: p1对象和p2对象中分别包含a对象和b对象, a对象和b对象中的字段是一致的, 并且在p1对象和p2对象中的属性名也是一致的, 这种情况下就需要使用json进行对象类型转化** @param fromObj     源对象* @param targetClazz 目标对象的类* @return P2* @author shy* @date: 2024/07/19 0:08*/public static <P1, P2> P2 convertByJackson(P1 fromObj, Class<P2> targetClazz) {return CONVERTOR_MAPPER.convertValue(fromObj, targetClazz);}/*** 将 源列表 中的对象拷贝到新目标类列表中。* 返回值的泛型根据接受参数决定* 基于 JSON 序列化和反序列化,可以处理更复杂的类型转换* 例如: p1对象和p2对象中分别包含a对象和b对象, a对象和b对象中的字段是一致的, 并且在p1对象和p2对象中的属性名也是一致的, 这种情况下就需要使用json进行对象类型转化** @param fromList    源列表* @param targetClazz 目标对象的泛型* @return List<C2>* @author shy* @date: 2024/07/19 0:08*/public static <C1, C2> List<C2> convertListByJackson(List<C1> fromList, Class<C2> targetClazz) {CollectionType collectionType = CONVERTOR_MAPPER.getTypeFactory().constructCollectionType(List.class, targetClazz);return CONVERTOR_MAPPER.convertValue(fromList, collectionType);}
}

现在,让我们详细介绍这个类中的每个方法,并提供相应的使用示例。

1. convertTo 方法

convertTo方法用于将一个对象转换为另一个类型的对象。它使用Spring框架的BeanUtils.copyProperties方法来复制属性。

示例:

public class Person {private String name;private int age;// getters and setters
}public class PersonDTO {private String name;private int age;// getters and setters
}// 使用示例
Person person = new Person();
person.setName("John");
person.setAge(30);PersonDTO personDTO = BeanConvertor.convertTo(person, PersonDTO.class);
System.out.println(personDTO.getName()); // 输出: John
System.out.println(personDTO.getAge());  // 输出: 30

2. convertListTo 方法

convertListTo方法用于将一个对象列表转换为另一个类型的对象列表。它内部使用convertTo方法来转换每个对象。

示例:

List<Person> personList = new ArrayList<>();
personList.add(new Person("John", 30));
personList.add(new Person("Alice", 25));List<PersonDTO> personDTOList = BeanConvertor.convertListTo(personList, PersonDTO.class);
for (PersonDTO dto : personDTOList) {System.out.println(dto.getName() + ": " + dto.getAge());
}
// 输出:
// John: 30
// Alice: 25

3. convertByJackson 方法

convertByJackson方法使用Jackson库来进行对象转换。这种方法特别适用于处理嵌套对象的情况。

示例:

public class Address {private String street;private String city;// getters and setters
}public class AddressDto {private String street;private String city;// getters and setters
}public class Employee {private String name;private Address address;// getters and setters
}public class EmployeeDTO {private String name;private AddressDto address;// getters and setters
}// 使用示例
Employee employee = new Employee();
employee.setName("John");
Address address = new Address();
address.setStreet("123 Main St");
address.setCity("New York");
employee.setAddress(address);EmployeeDTO employeeDTO = BeanConvertor.convertByJackson(employee, EmployeeDTO.class);
System.out.println(employeeDTO.getName()); // 输出: John
System.out.println(employeeDTO.getAddress().getStreet()); // 输出: 123 Main St
System.out.println(employeeDTO.getAddress().getCity()); // 输出: New York

4. convertListByJackson 方法

convertListByJackson方法使用Jackson库来转换对象列表。这种方法同样适用于处理包含嵌套对象的列表。

示例:

List<Employee> employeeList = new ArrayList<>();
employeeList.add(new Employee("John", new Address("123 Main St", "New York")));
employeeList.add(new Employee("Alice", new Address("456 Elm St", "Los Angeles")));List<EmployeeDTO> employeeDTOList = BeanConvertor.convertListByJackson(employeeList, EmployeeDTO.class);
for (EmployeeDTO dto : employeeDTOList) {System.out.println(dto.getName() + ": " + dto.getAddress().getStreet() + ", " + dto.getAddress().getCity());
}
// 输出:
// John: 123 Main St, New York
// Alice: 456 Elm St, Los Angeles

5. 内容关联

大家也可以结合这篇文章, 使用FastJson完成对类中字段类型不一致的属性进行拷贝

Java中对象的拷贝之字段类型不一致

在这里插入图片描述

总结

BeanConvertor工具类提供了一种简单而强大的方式来处理Java对象之间的转换。它不仅可以处理简单的对象转换,还可以通过Jackson库处理更复杂的嵌套对象转换。这个工具类可以大大简化我们的代码,提高开发效率,并减少因手动转换可能引入的错误。

在实际开发中,你可能需要根据项目的具体需求来调整或扩展这个工具类。例如,你可能需要添加更多的错误处理,或者支持更多的转换场景。无论如何,这个BeanConvertor类为对象转换提供了一个很好的起点。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com