聊聊Lombok中的@Builder注解使用教程
更新時間:2021年11月17日 11:11:12 作者:殺手不太冷!
@Builder注解的作用主要是用來生成對象,并且可以為對象鏈式賦值。接下來通過本文給大家介紹Lombok中的@Builder注解使用教程,感興趣的朋友一起看看吧
Lombok中的@Builder注解的使用
作用
@Builder注解的作用主要是用來生成對象,并且可以為對象鏈式賦值。
引入依賴
因為@Builder注解是lombok中的東西,所以第一步我們需要引入lombok的依賴,如下圖:

第二步給實體類加上@Builder注解
第二步我們需要給我們的實體類加上一個@Builder注解,如下圖:

第三步使用測試使用@Builder注解生成對象

實體類加上@Builder注解之后的編譯結果
實體類加上@Builder注解之后,編譯之后會多出一個builder()方法,和一個CardBuilder靜態(tài)內部類,如下圖:


代碼如下:
public class Card {
private int id;
private String name;
private boolean sex;
public static Card.CardBuilder builder() {
return new Card.CardBuilder();
}
public Card(int id, String name, boolean sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
public Card() {
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public boolean isSex() {
return this.sex;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Card)) {
return false;
} else {
Card other = (Card)o;
if (!other.canEqual(this)) {
return false;
} else if (this.getId() != other.getId()) {
return false;
} else {
Object this$name = this.getName();
Object other$name = other.getName();
if (this$name == null) {
if (other$name == null) {
return this.isSex() == other.isSex();
}
} else if (this$name.equals(other$name)) {
return this.isSex() == other.isSex();
}
return false;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof Card;
}
public int hashCode() {
int PRIME = true;
int result = 1;
int result = result * 59 + this.getId();
Object $name = this.getName();
result = result * 59 + ($name == null ? 43 : $name.hashCode());
result = result * 59 + (this.isSex() ? 79 : 97);
return result;
}
public String toString() {
return "Card(id=" + this.getId() + ", name=" + this.getName() + ", sex=" + this.isSex() + ")";
}
public static class CardBuilder {
private int id;
private String name;
private boolean sex;
CardBuilder() {
}
public Card.CardBuilder id(int id) {
this.id = id;
return this;
}
public Card.CardBuilder name(String name) {
this.name = name;
return this;
}
public Card.CardBuilder sex(boolean sex) {
this.sex = sex;
return this;
}
public Card build() {
return new Card(this.id, this.name, this.sex);
}
public String toString() {
return "Card.CardBuilder(id=" + this.id + ", name=" + this.name + ", sex=" + this.sex + ")";
}
}
}
到此這篇關于Lombok中的@Builder注解的使用的文章就介紹到這了,更多相關Lombok @Builder注解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
java實現pdf文件截圖的方法【附PDFRenderer.jar下載】
這篇文章主要介紹了java實現pdf文件截圖的方法,結合實例形式分析了java基于PDFRenderer.jar進行pdf文件截圖的相關操作技巧,并附帶PDFRenderer.jar文件供讀者下載使用,需要的朋友可以參考下2018-01-01

