在实际项目中,我们常常需要把两个相似的对象相互转换,其目的是在对外提供数据时需要将一部分敏感数据(例如:密码、加密 token 等)隐藏起来
多用于DTO VO DO 对象转换
需要用到的jar
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper --> <dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> <version>2.3.8</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>
@Data @AllArgsConstructor @NoArgsConstructor public class StudentDTO { private Integer id; private String name; private Integer age; private String email; //订单号 private String orderNo; }
@Data public class StudentVO { private Integer id; private String name; private Integer age; private String email; }
需求将 DTO 转换成 VO (对象状态,集合状态)
public class MyServiceImpl { public static StudentDTO studentDTO; public static List<StudentDTO> dList; static { studentDTO = new StudentDTO(); studentDTO.setId(111); studentDTO.setName("张三"); studentDTO.setAge(18); studentDTO.setEmail("abe@163.com"); studentDTO.setOrderNo("2020123567"); dList = new ArrayList<StudentDTO>(); StudentDTO s1 = new StudentDTO(222, "lisi", 28, "345@163", "345"); StudentDTO s2 = new StudentDTO(333, "zhaoliu", 38, "567@163", "567"); dList.add(s1); dList.add(s2); } /*** * 方式一 modeMapper 对象状态 */ @Test public void test() { System.out.println(studentDTO); ModelMapper modelMapper = new ModelMapper(); StudentVO student = modelMapper.map(studentDTO, StudentVO.class); System.out.println(student.toString()); } /*** * 方式一 modeMapper list */ @Test public void test2() { ModelMapper modelMapper = new ModelMapper(); List<StudentVO> vList = modelMapper.map(dList, new TypeToken<List<StudentDTO>>() { }.getType()); System.out.println(vList); } /*** * 方式二 BeanUtils (spring的) 对象状态 */ @Test public void test3() { StudentVO studentVO = new StudentVO(); BeanUtils.copyProperties(studentDTO,studentVO); System.out.println(studentVO); } /*** * 方式二 BeanUtils (spring的) list */ @Test public void test4() { List<StudentVO> studentVOList = dList.stream().map(t -> { StudentVO studentVO = new StudentVO(); BeanUtils.copyProperties(t, studentVO); return studentVO; }).collect(Collectors.toList()); System.out.println(studentVOList); } }