Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
spice (up):
to add interest or excitement to (something) — usually + up
- They looked for advice on how to spice up their living room.他们征求意见,看如何给客厅增添点情趣。
- We need to spice up our relationship.我们需要调剂一下我们的关系。
- We tried to spice things up by putting on some lively music.我们想放点欢快的音乐来助兴。
@Data
public class Account {
private int id;
private String name;
private int age;
private String gender;
private String password;
private String description;
}上面代码class反编译后的的代码为
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
public class Account {
private int id;
private String name;
private int age;
private String gender;
private String password;
private String description;
public static void main(String[] args) {
new Account();
}
@Generated
public Account() {
}
@Generated
public int getId() {
return this.id;
}
@Generated
public String getName() {
return this.name;
}
@Generated
public int getAge() {
return this.age;
}
@Generated
public String getGender() {
return this.gender;
}
@Generated
public String getPassword() {
return this.password;
}
@Generated
public String getDescription() {
return this.description;
}
@Generated
public void setId(int id) {
this.id = id;
}
@Generated
public void setName(String name) {
this.name = name;
}
@Generated
public void setAge(int age) {
this.age = age;
}
@Generated
public void setGender(String gender) {
this.gender = gender;
}
@Generated
public void setPassword(String password) {
this.password = password;
}
@Generated
public void setDescription(String description) {
this.description = description;
}
@Generated
public boolean equals(Object o) {
// ....
}
@Generated
protected boolean canEqual(Object other) {
return other instanceof Account;
}
@Generated
public int hashCode() {
// ...
}
@Generated
public String toString() {
int var10000 = this.getId();
return "Account(id=" + var10000 + ", name=" + this.getName() + ", age=" + this.getAge() + ", gender=" + this.getGender() + ", password=" + this.getPassword() + ", description=" + this.getDescription() + ")";
}
}可以看到lombok干涉了编译的过程
那么Lombok是如何做到一个注解就包揽了代码生成工作的呢?这里又要说到我们Java的编译过程,它可以分成三个阶段:
Drawing 2025-07-18 00.24.35.excalidraw
⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠ You can decompress Drawing data with the command palette: ‘Decompress current Excalidraw file’. For more info check in plugin settings under ‘Saving’
Excalidraw Data
Text Elements
java
source
code010111010101100010
Binary Files
Parse and Enter
Annotation
ProcessingAnalyse and
Link to original
Generate
- 所有源文件会被解析成语法树。
- 调用注解处理器。如果注解处理器产生了新的源文件,新文件也要进行编译。
- 最后,语法树会被分析并转化成类文件。
Lombok会在上述的第二阶段,执行lombok.core.AnnotationProcessor,它所做的工作就是我们上面所说的,修改语法树,并将注解对应需要生成的内容全部添加到类文件中,这样,我们即使没有在源代码中编写的内容,也会存在于生成出来的class文件中。