lombok的使用
2018-10-21 本文已影响0人
木棍兒
在IDE中添加lombok插件
在idea中安装lombok插件


在eclipse中安装lombok插件
下载lombok.jar包https://projectlombok.org/download.html


在pom文件中添加依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.8</version>
</dependency>
lombok常用注解
-
@Getter,@Setter。注解可以针对类的属性字段自动生成Get/Set方法。
位于类上方.png
位于属性上方.png
上面的写法相当于这样写

2.@NoArgsConstructor,@AllArgsConstructor。注解为类自动生成了无参构造方法、和包含所有参数的构造方法。

上面的写法相当于这样写

3.@Data。生成get,set,toString,equals,hashCode,canEqual方法

上面的写法相当于
public class Booth {
private String name;
private String remark;
public Booth() {
}
public String getName() {
return this.name;
}
public String getRemark() {
return this.remark;
}
public void setName(String name) {
this.name = name;
}
public void setRemark(String remark) {
this.remark = remark;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Booth)) {
return false;
} else {
Booth other = (Booth)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$remark = this.getRemark();
Object other$remark = other.getRemark();
if (this$remark == null) {
if (other$remark != null) {
return false;
}
} else if (!this$remark.equals(other$remark)) {
return false;
}
return true;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof Booth;
}
public int hashCode() {
int PRIME = true;
int result = 1;
Object $name = this.getName();
int result = result * 59 + ($name == null ? 43 : $name.hashCode());
Object $remark = this.getRemark();
result = result * 59 + ($remark == null ? 43 : $remark.hashCode());
return result;
}
public String toString() {
return "Booth(name=" + this.getName() + ", remark=" + this.getRemark() + ")";
}
}
4.@Builder。提供builder设计模式的实现。
@Builder
public class Booth {
private String name;
private String remark;
}
在获取Booth对象时
private Booth getBooth(String name, String remark){
Booth booth = Booth.builder()
.name(name)
.remark(remark)
.build();
return booth;
}
当使用@Builder时将不会自动生成无参构造方法(会生成一个全参数的构造方法)
@Builder,@NoArgsConstructor不能同时使用
原理


在编译过程中Source File(源代码文件)被转换成AST(抽象语法树)然后在注解处理过程中调用实现了JSR 269 API规范的lombok程序,lombok修改AST。修改后的AST会被解析并生成字节码文件。