lombok原理
工作了一年多了,在工作中使用Lombok节省了很多代码量,同时简化优化了代码结构,今天讲解一下lombok的原理。
1)在java中,注解的两种解析方式,一种是运行时解析,另一种是编译时解析,而lombok就是注解编译时解析。
编译时解析机制-Pluggable Annotation Processing API(JSR269插入式注解处理器),如下:
2)Lombok常见注解
常见方法-@Data
@Getter
@Setter
@ToString
@EqualsAndHashCode
构造方法
@AllArgsConstructor
@NoArgsConstructor
@RequiredArgsConstructor
自动为类添加日志支持-@Slf4j
自动生成try/catch捕捉异常-@SneakyThrows
自动生成同步锁-@Synchronized
自动生成构造这模式-@Builder
自动调用的close方法释放资源-@Cleanup
自动生成空值校验-@NonNull
3) 安装Lombok插件
在idea中安装lombok插件,为什么要在idea中安装lombok插件呢?lombok是工作在编译时期,利用注解处理器将代码中的注解解析之后会为我们生成一些代码。比如我们给一个类上加@Getter注解,没有实现get方法,idea实际上是搜索不到get方法的,这样编译器会报错,所以我们在使用lombok之前,要先安装lombok插件。
4)引入lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
添加<scope>provided</scope>,因为provided表明该包只在编译和测试的时候用
5)lombok的使用
在idea中 创建一个测试类Test.java,添加@Data注解
import lombok.Data;
/**
* 测试类
*/
@Data
public class Test {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
}
编译Test.java,得到Test.class文件,我们可以看到插入式注解处理器在解析到注解@Data时,为我们自动生成常见的方法:get、set、toString等等。
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
public class Test {
private String name;
private Integer age;
public Test() {
}
public String getName() {
return this.name;
}
public Integer getAge() {
return this.age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Test)) {
return false;
} else {
Test other = (Test)o;
if (!other.canEqual(this)) {
return false;
} else {
Object this$name = this.getName();
Object other$name = other.getName();
if (this$name == null) {
if (other$name != null) {
return false;
}
} else if (!this$name.equals(other$name)) {
return false;
}
Object this$age = this.getAge();
Object other$age = other.getAge();
if (this$age == null) {
if (other$age != null) {
return false;
}
} else if (!this$age.equals(other$age)) {
return false;
}
return true;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof Test;
}
public int hashCode() {
int PRIME = true;
int result = 1;
Object $name = this.getName();
int result = result * 59 + ($name == null ? 43 : $name.hashCode());
Object $age = this.getAge();
result = result * 59 + ($age == null ? 43 : $age.hashCode());
return result;
}
public String toString() {
return "Test(name=" + this.getName() + ", age=" + this.getAge() + ")";
}
}
6)lombok优缺点
lombok的优点
通过注解自动生成样板代码,提高开发效率
代码简洁,只关注相关属性
新增属性后,无需刻意修改相关方法
lombok的缺点
降低了源代码的可读性和完整性
加大对问题排查的难度
需要IDE的相关插件的支持
还没有评论,来说两句吧...