Java中对象复制list复制
在实际项⽬中,我们常常需要把两个相似的对象相互转换,其⽬的是在对外提供数据时需要将⼀部分敏感数据(例如:密码、加密 token 等)隐藏起来
多⽤于DTO VO DO 对象转换
需要⽤到的jar
<!-- mvnrepository/delmapper/modelmapper -->
<dependency>
<groupId&delmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.8</version>
</dependency>
<!-- mvnrepository/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!-- mvnrepository/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");
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.String());
}
/***
* ⽅式⼀ 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();
fastjson字符串转数组
System.out.println(studentVO);
}
/***
* ⽅式⼆ BeanUtils (spring的)  list
*/
@Test
public void test4() {
List<StudentVO> studentVOList = dList.stream().map(t -> {
StudentVO studentVO = new StudentVO();
return studentVO;
}).List());
System.out.println(studentVOList);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。