您的位置 首页 java

java 对象属性拷贝的小技巧

使用org.springframework.beans.BeanUtils.copyProperties方法进行对象之间属性的赋值,避免通过get、set方法一个一个属性的赋值。

copyProperties(Object source, Object target) 对象属性拷贝,将源对象的属性拷贝到目标对象。

public User addUser(UserInputDTO userInputDTO){

User user = new User();

user.setUsername(userInputDTO.getUsername());

user.setAge(userInputDTO.getAge());

return userService.addUser(user);

}

使用 org.springframework.beans.BeanUtils#copyProperties 对代码进行重构和优化,BeanUtils.copyProperties 是一个浅拷贝方法,复制属性时,我们只需要把 DTO 对象和要转化的对象两个的属性值设置为一样的名称,并且保证一样的类型就可以了。

public User addUser(UserInputDTO userInputDTO){

User user = convertFor(userInputDTO);

return userService.addUser(user);

}

private User convertFor(UserInputDTO userInputDTO){

User user = new User();

BeanUtils.copyProperties(userInputDTO,user);

return user;

}

文章来源:智云一二三科技

文章标题:java 对象属性拷贝的小技巧

文章地址:https://www.zhihuclub.com/181782.shtml

关于作者: 智云科技

热门文章

网站地图