当前位置:网站首页>Lombok makes ⽤ @data and @builder's pit at the same time. Are you hit?
Lombok makes ⽤ @data and @builder's pit at the same time. Are you hit?
2022-07-07 00:36:00 【Java collection】
The problem background
Lombok Use Use at the same time @Data and @Builder , An error is reported when constructing a parameterless constructor ! Compile not pass . Here's the picture :

Lombok @Data and @Builder Analyze usage separately
Lombok Use @Data Sure ⽣ become ⽆ Participate in constructing classes ⾥⾯ All attributes of getter/setter Method . It can simplify the development of our code .( Need to install Lombok Plug ins and leads ⼊Lombok rely on ).
For example, next ⾯ Of ⼀ Entity classes , lead ⼊Lombok after , Sure ⾃ dynamic ⽣ become GET/SET Methods and ⽆ Parameter constructor .

The compiled class by : You can see that it not only helps us generate get and set , There is also a default parameterless constructor

So how to automatically generate a parameter constructor ? Use @Builder annotation , Will help us ⽣ The construction method of completion attribute .

The compiled class by : You can see It has helped us build a full attribute constructor , But if the value only references @Builder Annotations cannot be generated get and set Of . in addition , public Number Java selected , reply java interview , Access to interview information .

But if used at the same time @Data and @Builder Words , It can be seen that although ⽣ a GET/SET Method , however ⽆ The parameter construction method is gone , This is obviously unacceptable , Because many frameworks call ⽆ Reference structure to create objects .

The compiled class:

We try to be in Tet1 class ,⼿ Dynamic add ⽆ Refer to the construction method . The compiler finds that an error is reported and fails :

resolvent
Method 1
Lombok Use at the same time @Data and @Builder When , If you want to ⽣ become ⽆ Reference structure , Need to be in code ⾥⾯⼿ Dynamic leading ⼊ annotation @Tolerate, Give Way Lombok stay ⽣ When you are in a class , Not aware of the specified constructor .

Method 2
Use the parameterless constructor directly + There is a way of involving constructors ,@RequiredArgsConstructor To build a reference ,@NoArgsConstructor To build a parameterless constructor , As shown in the figure :

The effect after compiling :

Lombok principle
Java The compilation of is divided into the following ⼏ Stages :
Parsing and filling symbol tables -> Annotation Processing -> Analysis and bytecode ⽣ become ->⽣ become ⼆ Base number class⽂ Pieces of .
Lombok It uses JDK 6 Realized
JSR 269: Pluggable Annotation Processing API( Compile time annotation processor ), It is in compile time to put Lombok The annotation code for , Convert to regular Java Method ⽽ Implementation note ⼊.At compile time , When Java Source code is abstract idiom tree (AST) after ,Lombok Will be based on ⾃⼰ The annotation processor dynamically modifies AST, Add new code ( node ), Here ⼀ Cut hold ⾏ after , And then through the analysis ⽣ It becomes the final bytecode (.class) ⽂ Pieces of , This is it. Lombok The hold of ⾏ principle .
It can be implemented with the help of annotation processor ⼀ A simple one. Setter, Our implementation steps are :
Customize ⼀ An annotation tag is attached to ⼝, And implement ⼀ individual ⾃ Defined annotation handler ;
utilize tools.jar Of javac api Handle AST ( Abstract syntax tree )3. Use ⾃ The defined annotation handler compiles the code .
1. Define custom annotations and annotation handlers
⾸ First create ⼀ individual MySetter.java ⾃ Definition ⼀ A note , The code is as follows :

Re realization ⼀ individual ⾃ Defined annotation handler , The code is as follows :



The test class is as follows :

2. To the annotation processor ⾏ compile , Then use the annotation processor to enter the class ⾏ compile
⾸ The annotation processor needs to be modified first ⾏ compile (javac -cp For leading ⼊ Third jar Baojin ⾏ compile )

Then use the annotation processor to process this Person Test class into ⾏ compile :
Let's look at it later ⽣ Yes Person.class, You can find Setter The method has been ⽣ a :


summary
Of course, although the test class has ⽣ become Setter Method , But because it is at compile time ⽣ Yes , Therefore, we cannot call directly when developing Setter Methodical , therefore Lombok Provides plug-in mechanism , We can call directly when developing Lombok Characteristics of .
author : Shudongjun
https://juejin.cn/post/7103011031672176677
official account “ Big coffee notes ” 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! !
边栏推荐
- How to use vector_ How to use vector pointer
- 37 pages Digital Village revitalization intelligent agriculture Comprehensive Planning and Construction Scheme
- Data analysis course notes (V) common statistical methods, data and spelling, index and composite index
- 【CVPR 2022】目标检测SOTA:DINO: DETR with Improved DeNoising Anchor Boxes for End-to-End Object Detection
- 【软件逆向-自动化】逆向工具大全
- 准备好在CI/CD中自动化持续部署了吗?
- Explain in detail the implementation of call, apply and bind in JS (source code implementation)
- AI super clear repair resurfaces the light in Huang Jiaju's eyes, Lecun boss's "deep learning" course survival report, beautiful paintings only need one line of code, AI's latest paper | showmeai info
- DAY SIX
- Encryption algorithm - password security
猜你喜欢

ldap创建公司组织、人员

Imeta | Chen Chengjie / Xia Rui of South China Agricultural University released a simple method of constructing Circos map by tbtools

Hero League | King | cross the line of fire BGM AI score competition sharing

Data analysis course notes (V) common statistical methods, data and spelling, index and composite index

37 pages Digital Village revitalization intelligent agriculture Comprehensive Planning and Construction Scheme

509 certificat basé sur Go

如何判断一个数组中的元素包含一个对象的所有属性值

Geo data mining (III) enrichment analysis of go and KEGG using David database

沉浸式投影在线下展示中的三大应用特点

Understand the misunderstanding of programmers: Chinese programmers in the eyes of Western programmers
随机推荐
Matlab learning notes
刘永鑫报告|微生物组数据分析与科学传播(晚7点半)
File and image comparison tool kaleidoscope latest download
Liuyongxin report | microbiome data analysis and science communication (7:30 p.m.)
【软件逆向-自动化】逆向工具大全
The programmer resigned and was sentenced to 10 months for deleting the code. Jingdong came home and said that it took 30000 to restore the database. Netizen: This is really a revenge
Leecode brush questions record sword finger offer 11 Rotate the minimum number of the array
Three sentences to briefly introduce subnet mask
stm32F407-------SPI通信
37頁數字鄉村振興智慧農業整體規劃建設方案
Web project com mysql. cj. jdbc. Driver and com mysql. jdbc. Driver differences
工程师如何对待开源 --- 一个老工程师的肺腑之言
Advanced learning of MySQL -- basics -- multi table query -- external connection
How can computers ensure data security in the quantum era? The United States announced four alternative encryption algorithms
dynamic programming
Leecode brush questions record sword finger offer 44 A digit in a sequence of numbers
Jenkins' user credentials plug-in installation
[CVPR 2022] target detection sota:dino: Detr with improved detecting anchor boxes for end to end object detection
js导入excel&导出excel
[CVPR 2022] semi supervised object detection: dense learning based semi supervised object detection