当前位置:网站首页>Interviewer: you use Lombok every day. What is its principle? I can't answer
Interviewer: you use Lombok every day. What is its principle? I can't answer
2022-06-27 06:50:00 【xy29981】
Lombok How to use
function
Compile time annotations
Annotation processing tools apt
Definition notes
Define annotation handler
Define classes that use annotations ( Test class )
I believe that everyone has used Lombok, Because it can simplify a lot of our code , But there are a lot of functions to have .
that lombok What is it ,lombok It is a simple annotation to help us simplify and eliminate some necessary but bloated Java Code tools , Simply speaking , For example, we create a new class , Then I write a few fields in it , And then usually we need to manually create getter and setter Methods: , Constructors and so on ,lombok To save us the trouble of creating the code manually , It can automatically generate these methods when we compile the source code .
that Lombok How do you do it ? In fact, the bottom layer is the use of compile time annotation function .
Lombok How to use
Lombok It's an open source project , The code is in lombok in , If it is gradle The project can be directly quoted as follows in the project .
compile ("org.projectlombok:lombok:1.16.6")
function
that Lombok What is it for ? It's very simple , One of the simplest examples is the ability to automatically generate methods by adding annotations , Make our code more concise and easy to understand . For example, the following class .
1 @Data
2 public class TestLombok {
3 private String name;
4 private Integer age;
5
6 public static void main(String[] args) {
7 TestLombok testLombok = new TestLombok();
8 testLombok.setAge(12);
9 testLombok.setName("zs");
10 }
11 }
We use Lombok Provided Data annotation , Without writing get、set Methods can also be used get、set Method . Let's look at the compiled class file , You can see that it's automatically generated for us get、set Method .
1 public class TestLombok {
2 private String name;
3 private Integer age;
4
5 public static void main(String[] args) {
6 TestLombok testLombok = new TestLombok();
7 testLombok.setAge(12);
8 testLombok.setName("zs");
9 }
10
11 public TestLombok() {
12 }
13
14 public String getName() {
15 return this.name;
16 }
17
18 public Integer getAge() {
19 return this.age;
20 }
21
22 public void setName(String name) {
23 this.name = name;
24 }
25
26 public void setAge(Integer age) {
27 this.age = age;
28 }
29
30}
Of course Lombok More than that , There are many other annotations that help us develop easily , There is a lot of information on the Internet about Lombok How to use , There's no more verbosity here . Normally, we customize annotations in the project , Or use Spring In the frame @Controller、@Service Wait a minute. All these annotations are Runtime annotations , Runtime annotations are mostly implemented through reflection . and Lombok It's implemented using compile time annotations . So what are compile time annotations ?
Compile time annotations
annotation ( Also known as metadata ) Provides a formal way for us to add information to our code , This makes it very convenient for us to use this data at a later time .—————— Excerpt from 《Thinking in Java》
Java The notes in are divided into Runtime annotations and Compile time annotations , Runtime annotation is the information that we often use to get our annotation through reflection when the program is running , And then do some operations . What are compiler time annotations ? It is to be processed by annotation processor during compilation .
Compile time :Java The compile time of a language is an uncertain process , Because it could be
*.javaFile to*.classDocumentation process ; It may also refer to the process of converting bytecode into machine code ; It may also be that it will directly*.javaThe process of compiling into local machine codeThe run-time : from JVM Load bytecode file into memory , The process of unloading after the final use belongs to the category of runtime .
Annotation processing tools apt
Annotation processing tools apt(Annotation Processing Tool), This is a Sun Tools provided to help with annotation processing ,apt Designed to operate Java Source file , Instead of a compiled class .
It is javac A tool for , Compile time annotation processor .APT Can be used to scan and process annotations at compile time . adopt APT You can get information about annotations and annotated objects , After getting this information, we can automatically generate some code according to the requirements , No manual writing . Be careful , Getting annotations and generating code are all in code compile It was time to finish , Compared with reflection, it greatly improves program performance by processing annotations at run time .APT The core is AbstractProcessor class .
Use under normal circumstances APT The tool can only generate some files ( It's not just our imagination class file , It also includes xml Documents and so on ), Can't modify the original file information .
But at this point, it is expected that there will be doubts , that Lombok Isn't it just adding some information to our original file ? I'll explain it in detail later , Here is a brief introduction , Actually Lombok It was modified Java Medium Abstract syntax tree AST To modify the information of its original class .
Now let's show you how to use APT Tools generate a class file , Then we'll talk about Lombok How to modify the properties of an existing class .
Definition notes
First of all, of course, we need to define our own annotations
1 @Retention(RetentionPolicy.SOURCE)
2 @Target(ElementType.TYPE)
3 public @interface GeneratePrint {
4
5 String value();
6 }
Retention The annotation has an attribute value, It is RetentionPolicy Enumeration class of type ,RetentionPolicy There are three values in the enumeration class .
1 public enum RetentionPolicy {
2
3 SOURCE,
4
5 CLASS,
6
7 RUNTIME
8 }
SOURCEEmbellished notes : Embellished notes , Information that represents annotations is discarded by the compiler , Will not stay class In file , The annotation information will only remain in the source fileCLASSEmbellished notes : The information indicating the annotation is retained in class file ( Bytecode file ) When the program is compiled , But will not be read by the virtual machine at run timeRUNTIMEEmbellished notes : The information indicating the annotation is retained in class file ( Bytecode file ) When the program is compiled , Will be retained by the virtual machine at runtime . So it can call... Through reflection , So normal runtime annotations use this parameter
Target There is also an attribute on the annotation value, It is ElementType Enumeration of types . It is used to modify where the annotation works .
1 public enum ElementType {
2 TYPE,
3
4 FIELD,
5
6 METHOD,
7
8 PARAMETER,
9
10 CONSTRUCTOR,
11
12 LOCAL_VARIABLE,
13
14 ANNOTATION_TYPE,
15
16 PACKAGE,
17
18 TYPE_PARAMETER,
19
20 TYPE_USE
21 }
Define annotation handler
If we want to define annotation processors , Then we need to inherit AbstractProcessor class . After inheritance, the basic framework types are as follows
1 @SupportedSourceVersion(SourceVersion.RELEASE_8)
2 @SupportedAnnotationTypes("aboutjava.annotion.MyGetter")
3 public class MyGetterProcessor extends AbstractProcessor {
4 @Override
5 public synchronized void init(ProcessingEnvironment processingEnv) {
6 super.init(processingEnv);
7 }
8
9 @Override
10 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
11 return true;
12 }
13 }
We can see that there are two annotations in the subclass , The notes are described as follows
@SupportedSourceVersion: To express support for Java edition@SupportedAnnotationTypes: Represents the annotation to be processed by the processor
Inherits two methods from the parent class , The method is described as follows
init Method : It is mainly to obtain some environment information during the compilation period
process Method : At compile time , The method of compiler execution . That's where we write the concrete logic
We're going to show you how to use inheritance AbstractProcessor Class to generate classes at compile time , So we are process Method to write our generated class code . As shown below .
1 @Override
2 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
3 StringBuilder builder = new StringBuilder()
4 .append("package aboutjava.annotion;\n\n")
5 .append("public class GeneratedClass {\n\n")
6 .append("\tpublic String getMessage() {\n")
7 .append("\t\treturn \"");
8
9 for (Element element : roundEnv.getElementsAnnotatedWith(MyGetter.class)) {
10 String objectType = element.getSimpleName().toString();
11
12 builder.append(objectType).append(" says hello!\\n");
13 }
14 builder.append("\";\n")
15 .append("\t}\n")
16 .append("}\n");
17 try {
18 JavaFileObject source = processingEnv.getFiler().createSourceFile("aboutjava.annotion.GeneratedClass");
19 Writer writer = source.openWriter();
20 writer.write(builder.toString());
21 writer.flush();
22 writer.close();
23 } catch (IOException e) {
24
25
26 }
27 return true;
28 }
Define classes that use annotations ( Test class )
The two classes above are the basic tool classes , One is defining annotations , One is to define annotation processors , Next, let's define a test class (TestAno.java). We add our own annotation class to the class .
1 @MyGetter
2 public class TestAno {
3
4 public static void main(String[] args) {
5 System.out.printf("1");
6 }
7 }
So we can generate files at compile time , Let's show you how to generate files at compile time , Don't be in a hurry right now javac compile ,MyGetter Class is annotation class. That's right , and MyGetterProcessor Is the annotation class processor , So we're compiling TestAnoJava The processor will be triggered when the file is in progress . So these two classes cannot be compiled together .
Let me show you my directory structure first
aboutjava2
-- annotion3
-- MyGetter.java4
-- MyGetterProcessor.java5
-- TestAno.java
So let's compile the annotation class and annotation processor class first
javac aboutjava/annotion/MyGett*
Next we compile our test class , In this case, you need to add processor Parameters , Used to specify the associated annotation processing class .
javac -processor aboutjava.annotion.MyGetterProcessor aboutjava/annotion/TestAno.java
You can see in the dynamic diagram , Automatically generated Java file .

picture
Please look forward to my next article , thank you .

more java Advanced information , Interview information , Official account
边栏推荐
- 获取地址url中的query参数指定参数方法
- Quick realization of Bluetooth ibeacn function
- Distribution gaussienne, régression linéaire, régression logistique
- 面试官:用分库分表如何做到永不迁移数据和避免热点问题?
- TiDB的使用限制
- How to write controller layer code gracefully?
- pytorch Default process group is not initialized
- Classical cryptosystem -- substitution and replacement
- [cultivation system] common regular expressions
- Meaning of 0.0.0.0:x
猜你喜欢

研究生数学建模竞赛-无人机在抢险救灾中的优化应用

Classical cryptosystem -- substitution and replacement

Caldera installation and simple use

面试官:请你介绍一下缓存穿透、缓存空值、缓存雪崩、缓存击穿的,通俗易懂

Unsafe中的park和unpark

Distribution gaussienne, régression linéaire, régression logistique
![[QT] use structure data to generate read / write configuration file code](/img/f4/685315c92f4e2528652532445fb519.png)
[QT] use structure data to generate read / write configuration file code

OpenCV怎么下载?OpenCV下载后怎么配置?

vs怎么配置OpenCV?2022vs配置OpenCV详解(多图)

Us camera cloud service scheme: designed for lightweight video production scenes
随机推荐
[cultivation system] common regular expressions
Assembly language - Wang Shuang Chapter 11 flag register - Notes
How to write controller layer code gracefully?
OPPO面试整理,真正的八股文,狂虐面试官
Unsafe中的park和unpark
AHB2APB桥接器设计(2)——同步桥设计的介绍
HTAP Quick Start Guide
高薪程序员&面试题精讲系列116之Redis缓存如何实现?怎么发现热key?缓存时可能存在哪些问题?
Redis cache penetration, cache breakdown, cache avalanche
可扩展哈希
Fast implementation of thread mesh networking
2018 mathematical modeling competition - special clothing design for high temperature operation
winow10安装Nexus nexus-3.20.1-01
Memory barrier store buffer, invalid queue
【毕业季】毕业是人生旅途的新开始,你准备好了吗
分数阶PID控制
Transaction overview of tidb
LeetCode 0086. Separate linked list
Machine learning
Classical cryptosystem -- substitution and replacement