当前位置:网站首页>Transform BeanUtils to achieve list data copy gracefully
Transform BeanUtils to achieve list data copy gracefully
2022-06-25 01:05:00 【Java collection】
Preface
BeanUtils.copyProperties(); It did do a lot for us , Although the deep copy cannot be completed perfectly , But for po、vo、dto A copy of is enough . But it still has some imperfections
Insufficient :
1. Can't copy list, And copy list There are a lot of cases , So there will be a lot of duplicate code .
for (S source : sources) {
T target = new T();
copyProperties(source, target);
list.add(target);
}2. There are some simple queries , You just need to switch vo Also needed new Vo()
public Vo findById(Integer id) {
Vo vo = new Vo();
Po po = dao.findById(id);
copyProperties(po, vo);
return vo;
}3. This copy method has no return value , Now? jdk8 Support stream() After the operation ( Reference resources :Jdk8 Stream), Support is not very friendly , inconvenient lambda Use of expressions .
So we decided to integrate BeanUtils class , Make yourself a handy wheel .
Use
We will create a new wheel BeanConvertUtils, Use as follows :
When we're going to switch po、vo when , It only needs , in addition , official account Java selected , reply java interview , Obtain interview question information .
// Before using
public Vo findById(Integer id) {
Vo vo = new Vo();
Po po = dao.findById(id);
copyProperties(po, vo);
return vo;
}
// After using
public Vo findById(Integer id) {
return BeanConvertUtils.converTo(dao.findById(id), Vo::new);
}
// After using , adopt lambda Expressions deal specifically with individual fields
public Vo findById(Integer id) {
return BeanConvertUtils.converTo(dao.findById(id), Vo::new,
(s, t) -> t.setName(s.getName))
);
}When we want to copy list It's also very simple
// Before using
public List<Vo> findAll() {
List<Vo> vos = new ArrayList();
List<Po> pos = dao.findAll();
for (Po po : Pos) {
Vo vo = new Vo();
BeanUtis.copyProperties(po, vo);
vos.add(vo);
}
return vos;
}
// After using
public List<Vo> findAll() {
return BeanConvertUtils.converToList(dao.findAll(), Vo::new)
}
// It also supports customization lambda
public List<Vo> findAll() {
return BeanConvertUtils.converToList(dao.findAll(), Vo::new,
(s, t) -> t.setName(s.getName))
)
}Code
/**
* Convert object tool
*
* @author bugpool
*/
public class BeanConvertUtils extends BeanUtils {
public static <S, T> T convertTo(S source, Supplier<T> targetSupplier) {
return convertTo(source, targetSupplier, null);
}
/**
* Convert objects , official account :Java selected
*
* @param source Source object
* @param targetSupplier Target object supplier
* @param callBack The callback method
* @param <S> Source object type
* @param <T> Target object type
* @return Target audience
*/
public static <S, T> T convertTo(S source, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) {
if (null == source || null == targetSupplier) {
return null;
}
T target = targetSupplier.get();
copyProperties(source, target);
if (callBack != null) {
callBack.callBack(source, target);
}
return target;
}
public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier) {
return convertListTo(sources, targetSupplier, null);
}
/**
* Convert objects
*
* @param sources Source object list
* @param targetSupplier Target object supplier
* @param callBack The callback method
* @param <S> Source object type
* @param <T> Target object type
* @return Target audience list
*/
public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) {
if (null == sources || null == targetSupplier) {
return null;
}
List<T> list = new ArrayList<>(sources.size());
for (S source : sources) {
T target = targetSupplier.get();
copyProperties(source, target);
if (callBack != null) {
callBack.callBack(source, target);
}
list.add(target);
}
return list;
}
/**
* Callback interface official account :Java selected
*
* @param <S> Source object type
* @param <T> Target object type
*/
@FunctionalInterface
public interface ConvertCallBack<S, T> {
void callBack(S t, T s);
}
}performance
Because only BeanUtils An encapsulation of , The performance is almost the same as that of the original code , If you want to say almost right , After all, there is an extra layer of function stack calls , But it is basically negligible . The main performance is still determined by BeanUtils decision .
remind
I don't know about this BeanConvertUtils How do you feel about tools , I used a lot in the project , Very convenient also . But there are two things to be reminded .
This method still can not solve the deep copy problem , Detailed can google once
BeanUtilsDeep copy problem ;If source perhaps
targetSupplierJust one for null, This tool class is not likeBeanUtilsThrow an exception like this , It's going back to null, Because I think that if the caller puts null Carry out quasi replacement , That is to convert to null, If it is not empty, it should be the responsibility of the caller .
Copyright notice : This paper is about CSDN Blogger 「bugpool」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
https://bugpool.blog.csdn.net/article/details/105620681
official account “Java selected ” The published content indicates the source of , All rights reserved ( Those whose copyright cannot be verified or whose source is not indicated all come from the Internet , Reprinted , The purpose of reprinting is to convey more information , The copyright belongs to the original author . If there is any infringement , Please contact the , The author will delete the first time !
Many people have asked recently , Is there any readers Communication group ! The way to join is simple , official account Java selected , reply “ Add group ”, You can join the group !
Java Interview questions ( Wechat applet ):3000+ The road test questions , contain Java Basics 、 Concurrent 、JVM、 Threads 、MQ series 、Redis、Spring series 、Elasticsearch、Docker、K8s、Flink、Spark、 Architecture design, etc , Brush questions online at any time !
------ Special recommendation ------
Special recommendation : Focus on the most cutting-edge information and technology sharing , Official account for preparing for overtaking on curves and various open source projects and efficient software ,「 Big coffee notes 」, Focus on finding good things , It's worth your attention . Click the official account card below to follow .
If the article helps , Click to see , Forward! !
边栏推荐
- [redis realizes seckill service ④] one order for one person, and cannot be purchased repeatedly
- 移动安全工具-apktool
- Custom animation (simulated win10 loading animation)
- 2021-04-18
- In the process of enterprise development, I found that a colleague used the select * from where condition for update
- 51 single chip microcomputer multi computer communication
- Scala classes inherit multiple attributes
- 【Redis实现秒杀业务③】超卖问题之乐观锁具体实现
- Go语言运算符(第8课下)
- The acceleration of 100 km is only 5.92 seconds, and the willanda high-performance version leads with the strength of high-energy products
猜你喜欢

【微服务|Sentinel】实时监控|RT|吞吐量|并发数|QPS

丹麥技術大學首創將量子計算應用於能源系統潮流建模

Using tcp/udp tools to debug the yeelight ribbon

Practical operation notes - notebook plus memory and ash cleaning

大厂高频软件测试面试题和答案都帮你准备好啦,备战金九银十

QT(35)-操作EXCEL-QXlsx-QAxObject
![[micro service sentinel] real time monitoring | RT | throughput | concurrency | QPS](/img/fc/6b36759570b9b1007d2640009576d9.png)
[micro service sentinel] real time monitoring | RT | throughput | concurrency | QPS

2022安全员-C证考试模拟100题及在线模拟考试

【Redis实现秒杀业务③】超卖问题之乐观锁具体实现

Scala IO reads by lexical units and numbers
随机推荐
A small crawler program written by beginners
Previous basic review
Sanic服务启动失败
Mobile security tool -dex2jar
Syntax highlighting of rich text
Scala trait construction mechanism
Scala sample class case calculate
【微服务|Sentinel】Sentinel快速入门|构建镜像|启动控制台
Can communication experiment between C and C
扎克伯格上手演示四款VR头显原型机,Meta透露元宇宙「家底」
【微服务|Sentinel】簇点链路|微服务集群环境搭建
Xcode预览(Preview)显示List视图内容的一个Bug及解决
Kubernetes 架构核心组件工作原理解析
[micro service sentinel] real time monitoring | RT | throughput | concurrency | QPS
[redis realizes seckill service ④] one order for one person, and cannot be purchased repeatedly
Golang示例续期锁:Redis+Channel+sync.Mutex
[microservices sentinel] sentinel quick start | building an image | starting the console
2022 melting welding and thermal cutting recurrent training question bank simulated examination platform operation
Scala classes inherit multiple attributes
智能合约安全审计入门篇 —— delegatecall (2)