当前位置:网站首页>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! !
边栏推荐
- Rails 4 asset pipeline vendor asset images are not precompiled
- Matlab learning notes
- Lombok 同时使⽤ @Data 和 @Builder 的坑,你中招没?
- 37頁數字鄉村振興智慧農業整體規劃建設方案
- 509 certificat basé sur Go
- A way of writing SQL, update when matching, or insert
- Geo data mining (III) enrichment analysis of go and KEGG using David database
- On February 19, 2021ccf award ceremony will be held, "why in Hengdian?"
- [CVPR 2022] target detection sota:dino: Detr with improved detecting anchor boxes for end to end object detection
- DAY FIVE
猜你喜欢
DAY FIVE
37頁數字鄉村振興智慧農業整體規劃建設方案
三维扫描体数据的VTK体绘制程序设计
DAY TWO
rancher集成ldap,实现统一账号登录
Idea automatically imports and deletes package settings
Article management system based on SSM framework
Interface master v3.9, API low code development tool, build your interface service platform immediately
GPIO簡介
Win10 startup error, press F9 to enter how to repair?
随机推荐
@TableId can‘t more than one in Class: “com.example.CloseContactSearcher.entity.Activity“.
基於GO語言實現的X.509證書
37页数字乡村振兴智慧农业整体规划建设方案
Mujoco produces analog video
uniapp实现从本地上传头像并显示,同时将头像转化为base64格式存储在mysql数据库中
Imeta | Chen Chengjie / Xia Rui of South China Agricultural University released a simple method of constructing Circos map by tbtools
Use package FY in Oracle_ Recover_ Data. PCK to recover the table of truncate misoperation
Three application characteristics of immersive projection in offline display
What can the interactive slide screen demonstration bring to the enterprise exhibition hall
Mujoco Jacobi - inverse motion - sensor
37 page overall planning and construction plan for digital Village revitalization of smart agriculture
Leecode brush questions record sword finger offer 11 Rotate the minimum number of the array
Uniapp uploads and displays avatars locally, and converts avatars into Base64 format and stores them in MySQL database
刘永鑫报告|微生物组数据分析与科学传播(晚7点半)
What is web penetration testing_ Infiltration practice
Encryption algorithm - password security
Google, Baidu and Yahoo are general search engines developed by Chinese companies_ Baidu search engine URL
37 pages Digital Village revitalization intelligent agriculture Comprehensive Planning and Construction Scheme
48 page digital government smart government all in one solution
Sword finger offer 26 Substructure of tree