Lombok外掛介紹、使用方法、工作原理和總結 侵立刪
轉自:https://www.cnblogs.com/heyonggang/p/8638374.html
1 Lombok背景介紹
官方介紹如下:
Project Lombok makes java a spicier language by adding 'handlers' that know how to build and compile simple, boilerplate-free, not-quite-java code.
大致意思是Lombok通過增加一些“處理程式”,可以讓java變得簡潔、快速。
2 Lombok使用方法
Lombok能以簡單的註解形式來簡化java程式碼,提高開發人員的開發效率。例如開發中經常需要寫的javabean,都需要花時間去新增相應的getter/setter,也許還要去寫構造器、equals等方法,而且需要維護,當屬性多時會出現大量的getter/setter方法,這些顯得很冗長也沒有太多技術含量,一旦修改屬性,就容易出現忘記修改對應方法的失誤。
Lombok能通過註解的方式,在編譯時自動為屬性生成構造器、getter/setter、equals、hashcode、toString方法。出現的神奇就是在原始碼中沒有getter和setter方法,但是在編譯生成的位元組碼檔案中有getter和setter方法。這樣就省去了手動重建這些程式碼的麻煩,使程式碼看起來更簡潔些。
Lombok的使用跟引用jar包一樣,可以在官網(https://projectlombok.org/download)下載jar包,也可以使用maven新增依賴:
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> <scope>provided</scope> </dependency>
接下來我們來分析Lombok中註解的具體用法。
2.1 @Data
@Data註解在類上,會為類的所有屬性自動生成setter/getter、equals、canEqual、hashCode、toString方法,如為final屬性,則不會為該屬性生成setter方法。
官方例項如下:
import lombok.AccessLevel; import lombok.Setter; import lombok.Data; import lombok.ToString; @Data public class DataExample { private final String name; @Setter(AccessLevel.PACKAGE) private int age; private double score; private String[] tags; @ToString(includeFieldNames=true) @Data(staticConstructor="of") public static class Exercise<T> { private final String name; private final T value; } }
如不使用Lombok,則實現如下:
import java.util.Arrays;
public class DataExample {
private final String name;
private int age;
private double score;
private String[] tags;
public DataExample(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
public void setScore(double score) {
this.score = score;
}
public double getScore() {
return this.score;
}
public String[] getTags() {
return this.tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
@Override public String toString() {
return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";
}
protected boolean canEqual(Object other) {
return other instanceof DataExample;
}
@Override public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof DataExample)) return false;
DataExample other = (DataExample) o;
if (!other.canEqual((Object)this)) return false;
if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
if (this.getAge() != other.getAge()) return false;
if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
return true;
}
@Override public int hashCode() {
final int PRIME = 59;
int result = 1;
final long temp1 = Double.doubleToLongBits(this.getScore());
result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
result = (result*PRIME) + this.getAge();
result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
return result;
}
public static class Exercise<T> {
private final String name;
private final T value;
private Exercise(String name, T value) {
this.name = name;
this.value = value;
}
public static <T> Exercise<T> of(String name, T value) {
return new Exercise<T>(name, value);
}
public String getName() {
return this.name;
}
public T getValue() {
return this.value;
}
@Override public String toString() {
return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")";
}
protected boolean canEqual(Object other) {
return other instanceof Exercise;
}
@Override public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Exercise)) return false;
Exercise<?> other = (Exercise<?>) o;
if (!other.canEqual((Object)this)) return false;
if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false;
if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false;
return true;
}
@Override public int hashCode() {
final int PRIME = 59;
int result = 1;
result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
result = (result*PRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode());
return result;
}
}
}
2.2 @Getter/@Setter
如果覺得@Data太過殘暴(因為@Data集合了@ToString、@EqualsAndHashCode、@Getter/@Setter、@RequiredArgsConstructor的所有特性)不夠精細,可以使用@Getter/@Setter註解,此註解在屬性上,可以為相應的屬性自動生成Getter/Setter方法,示例如下:
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
public class GetterSetterExample {
@Getter @Setter private int age = 10;
@Setter(AccessLevel.PROTECTED) private String name;
@Override public String toString() {
return String.format("%s (age: %d)", name, age);
}
}
如果不使用Lombok:
public class GetterSetterExample {
private int age = 10;
private String name;
@Override public String toString() {
return String.format("%s (age: %d)", name, age);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
protected void setName(String name) {
this.name = name;
}
}
2.3 @NonNull
該註解用在屬性或構造器上,Lombok會生成一個非空的宣告,可用於校驗引數,能幫助避免空指標。
示例如下:
import lombok.NonNull;
public class NonNullExample extends Something {
private String name;
public NonNullExample(@NonNull Person person) {
super("Hello");
this.name = person.getName();
}
}
不使用Lombok:
import lombok.NonNull;
public class NonNullExample extends Something {
private String name;
public NonNullExample(@NonNull Person person) {
super("Hello");
if (person == null) {
throw new NullPointerException("person");
}
this.name = person.getName();
}
}
2.4 @Cleanup
該註解能幫助我們自動呼叫close()方法,很大的簡化了程式碼。
示例如下:
import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
@Cleanup InputStream in = new FileInputStream(args[0]);
@Cleanup OutputStream out = new FileOutputStream(args[1]);
byte[] b = new byte[10000];
while (true) {
int r = in.read(b);
if (r == -1) break;
out.write(b, 0, r);
}
}
}
如不使用Lombok,則需如下:
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream(args[0]);
try {
OutputStream out = new FileOutputStream(args[1]);
try {
byte[] b = new byte[10000];
while (true) {
int r = in.read(b);
if (r == -1) break;
out.write(b, 0, r);
}
} finally {
if (out != null) {
out.close();
}
}
} finally {
if (in != null) {
in.close();
}
}
}
}
2.5 @EqualsAndHashCode
預設情況下,會使用所有非靜態(non-static)和非瞬態(non-transient)屬性來生成equals和hasCode,也能通過exclude註解來排除一些屬性。
示例如下:
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(exclude={"id", "shape"})
public class EqualsAndHashCodeExample {
private transient int transientVar = 10;
private String name;
private double score;
private Shape shape = new Square(5, 10);
private String[] tags;
private int id;
public String getName() {
return this.name;
}
@EqualsAndHashCode(callSuper=true)
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
}
2.6 @ToString
類使用@ToString註解,Lombok會生成一個toString()方法,預設情況下,會輸出類名、所有屬性(會按照屬性定義順序),用逗號來分割。
通過將includeFieldNames
引數設為true,就能明確的輸出toString()屬性。這一點是不是有點繞口,通過程式碼來看會更清晰些。
使用Lombok的示例:
import lombok.ToString;
@ToString(exclude="id")
public class ToStringExample {
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5, 10);
private String[] tags;
private int id;
public String getName() {
return this.getName();
}
@ToString(callSuper=true, includeFieldNames=true)
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
}
不使用Lombok的示例如下:
import java.util.Arrays;
public class ToStringExample {
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5, 10);
private String[] tags;
private int id;
public String getName() {
return this.getName();
}
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
@Override public String toString() {
return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
}
}
@Override public String toString() {
return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";
}
}
2.7 @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
無參構造器、部分引數構造器、全參構造器。Lombok沒法實現多種引數構造器的過載。
Lombok示例程式碼如下:
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.NonNull;
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class ConstructorExample<T> {
private int x, y;
@NonNull private T description;
@NoArgsConstructor
public static class NoArgsExample {
@NonNull private String field;
}
}
不使用Lombok的示例如下:
public class ConstructorExample<T> {
private int x, y;
@NonNull private T description;
private ConstructorExample(T description) {
if (description == null) throw new NullPointerException("description");
this.description = description;
}
public static <T> ConstructorExample<T> of(T description) {
return new ConstructorExample<T>(description);
}
@java.beans.ConstructorProperties({"x", "y", "description"})
protected ConstructorExample(int x, int y, T description) {
if (description == null) throw new NullPointerException("description");
this.x = x;
this.y = y;
this.description = description;
}
public static class NoArgsExample {
@NonNull private String field;
public NoArgsExample() {
}
}
}
3 Lombok工作原理分析
會發現在Lombok使用的過程中,只需要新增相應的註解,無需再為此寫任何程式碼。自動生成的程式碼到底是如何產生的呢?
核心之處就是對於註解的解析上。JDK5引入了註解的同時,也提供了兩種解析方式。
- 執行時解析
執行時能夠解析的註解,必須將@Retention設定為RUNTIME,這樣就可以通過反射拿到該註解。java.lang,reflect反射包中提供了一個介面AnnotatedElement,該介面定義了獲取註解資訊的幾個方法,Class、Constructor、Field、Method、Package等都實現了該介面,對反射熟悉的朋友應該都會很熟悉這種解析方式。
- 編譯時解析
編譯時解析有兩種機制,分別簡單描述下:
1)Annotation Processing Tool
apt自JDK5產生,JDK7已標記為過期,不推薦使用,JDK8中已徹底刪除,自JDK6開始,可以使用Pluggable Annotation Processing API來替換它,apt被替換主要有2點原因:
- api都在com.sun.mirror非標準包下
- 沒有整合到javac中,需要額外執行
2)Pluggable Annotation Processing API
JSR 269自JDK6加入,作為apt的替代方案,它解決了apt的兩個問題,javac在執行的時候會呼叫實現了該API的程式,這樣我們就可以對編譯器做一些增強,這時javac執行的過程如下:
Lombok本質上就是一個實現了“JSR 269 API”的程式。在使用javac的過程中,它產生作用的具體流程如下:
- javac對原始碼進行分析,生成了一棵抽象語法樹(AST)
- 執行過程中呼叫實現了“JSR 269 API”的Lombok程式
- 此時Lombok就對第一步驟得到的AST進行處理,找到@Data註解所在類對應的語法樹(AST),然後修改該語法樹(AST),增加getter和setter方法定義的相應樹節點
- javac使用修改後的抽象語法樹(AST)生成位元組碼檔案,即給class增加新的節點(程式碼塊)
拜讀了Lombok原始碼,對應註解的實現都在HandleXXX中,比如@Getter註解的實現時HandleGetter.handle()。還有一些其它類庫使用這種方式實現,比如Google Auto、Dagger等等。
4. Lombok的優缺點
優點:
- 能通過註解的形式自動生成構造器、getter/setter、equals、hashcode、toString等方法,提高了一定的開發效率
- 讓程式碼變得簡潔,不用過多的去關注相應的方法
- 屬性做修改時,也簡化了維護為這些屬性所生成的getter/setter方法等
缺點:
- 不支援多種引數構造器的過載
- 雖然省去了手動建立getter/setter方法的麻煩,但大大降低了原始碼的可讀性和完整性,降低了閱讀原始碼的舒適度
5. 總結
Lombok雖然有很多優點,但Lombok更類似於一種IDE外掛,專案也需要依賴相應的jar包。Lombok依賴jar包是因為編譯時要用它的註解,為什麼說它又類似外掛?因為在使用時,eclipse或IntelliJ IDEA都需要安裝相應的外掛,在編譯器編譯時通過操作AST(抽象語法樹)改變位元組碼生成,變向的就是說它在改變java語法。它不像spring的依賴注入或者mybatis的ORM一樣是執行時的特性,而是編譯時的特性。這裡我個人最感覺不爽的地方就是對外掛的依賴!因為Lombok只是省去了一些人工生成程式碼的麻煩,但IDE都有快捷鍵來協助生成getter/setter等方法,也非常方便。
知乎上有位大神發表過對Lombok的一些看法:
這是一種低階趣味的外掛,不建議使用。JAVA發展到今天,各種外掛層出不窮,如何甄別各種外掛的優劣?能從架構上優化你的設計的,能提高應用程式效能的 ,
實現高度封裝可擴充套件的..., 像lombok這種,像這種外掛,已經不僅僅是外掛了,改變了你如何編寫原始碼,事實上,少去了程式碼你寫上去又如何?
如果JAVA家族到處充斥這樣的東西,那隻不過是一坨披著金屬顏色的屎,遲早會被其它的語言取代。
雖然話糙但理確實不糙,試想一個專案有非常多類似Lombok這樣的外掛,個人覺得真的會極大的降低閱讀原始碼的舒適度。
雖然非常不建議在屬性的getter/setter寫一些業務程式碼,但在多年專案的實戰中,有時通過給getter/setter加一點點業務程式碼,能極大的簡化某些業務場景的程式碼。所謂取捨,也許就是這時的捨棄一定的規範,取得極大的方便。
我現在非常堅信一條理念,任何程式語言或外掛,都僅僅只是工具而已,即使工具再強大也在於用的人,就如同小米加步槍照樣能贏飛機大炮的道理一樣。結合具體業務場景和專案實際情況,無需一味追求高大上的技術,適合的才是王道。
Lombok有它的得天獨厚的優點,也有它避之不及的缺點,熟知其優缺點,在實戰中靈活運用才是王道。
參考:
https://projectlombok.org/features/
https://github.com/rzwitserloot/lombok?spm=a2c4e.11153940.blogcont59972.5.2aeb6d32hayLHv