当前位置:网站首页>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! !
边栏推荐
- Mobile security tool apktool
- Kibana installation via kubernetes visual interface (rancher)
- Source code analysis the problem that fragments cannot be displayed in the custom ViewGroup
- Realization of MNIST handwritten numeral recognition
- Leetcode 1248. Statistics of "graceful subarray" (harm, suddenly found that it can only enumerate violently)
- Custom animation (simulated win10 loading animation) - Optimization
- Tiktok wallpaper applet, starlight wallpaper applet version 2.0, upgraded version
- 重磅:国产IDE发布,由阿里研发,完全开源!(高性能+高定制性)
- 2022R1快开门式压力容器操作考题及答案
- ContentResolver,拿到手机短信内容
猜你喜欢

2022 crane driver (limited to bridge crane) examination question bank simulated examination platform operation

ros(25):rqt_ image_ View reports an error unable to load plugin for transport 'compressed', error string
![[micro service sentinel] real time monitoring | RT | throughput | concurrency | QPS](/img/fc/6b36759570b9b1007d2640009576d9.png)
[micro service sentinel] real time monitoring | RT | throughput | concurrency | QPS

QT electronic clock

Preliminary understanding of qtoolbutton

2022 simulated 100 questions of safety officer-c certificate examination and online simulated examination

生成订单30分钟未支付,则自动取消,该怎么实现?

2022熔化焊接与热切割复训题库模拟考试平台操作

使用 Loki 微服务模式部署生产集群

Kubernetes 架构核心组件工作原理解析
随机推荐
2022安全员-C证考试模拟100题及在线模拟考试
2022 melting welding and thermal cutting recurrent training question bank simulated examination platform operation
最新QQ微信域名防红PHP程序源码+强制跳转打开
Garbage collection of C closure
[redis realizes seckill service ②] solution to oversold problem
Scala trait exercise
A website for programmers with a monthly salary of 30K
51单片机多机通信
Sliding window technology based on byte in transport layer
QT(36)-rapidjson解析嵌套的json
【Redis实现秒杀业务④】一人一单,不可重复购买
Scala template method pattern
扎克伯格上手演示四款VR头显原型机,Meta透露元宇宙「家底」
Uniapp encapsulated incentive advertisement, screen insert advertisement and banner advertisement
大厂高频软件测试面试题和答案都帮你准备好啦,备战金九银十
2021-02-15
Single blind box removal, social blind box and friend blind box program source code
Mobile security tool -dex2jar
[microservices sentinel] sentinel quick start | building an image | starting the console
移动安全工具-jar