Lombok介紹、使用方法和總結

文章來源公衆號:猿人谷

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執行的過程如下:

123

Lombok本質上就是一個實現了“JSR 269 API”的程序。在使用javac的過程中,它產生作用的具體流程如下:

  1. javac對源代碼進行分析,生成了一棵抽象語法樹(AST)
  2. 運行過程中調用實現了“JSR 269 API”的Lombok程序
  3. 此時Lombok就對第一步驟得到的AST進行處理,找到@Data註解所在類對應的語法樹(AST),然後修改該語法樹(AST),增加getter和setter方法定義的相應樹節點
  4. javac使用修改後的抽象語法樹(AST)生成字節碼文件,即給class增加新的節點(代碼塊)

拜讀了Lombok源碼,對應註解的實現都在HandleXXX中,比如@Getter註解的實現時HandleGetter.handle()。還有一些其它類庫使用這種方式實現,比如Google AutoDagger等等。

4. Lombok的優缺點

優點:

  1. 能通過註解的形式自動生成構造器、getter/setter、equals、hashcode、toString等方法,提高了一定的開發效率
  2. 讓代碼變得簡潔,不用過多的去關注相應的方法
  3. 屬性做修改時,也簡化了維護爲這些屬性所生成的getter/setter方法等

缺點:

  1. 不支持多種參數構造器的重載
  2. 雖然省去了手動創建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

https://www.zhihu.com/question/42348457

https://blog.csdn.net/ghsau/article/details/52334762

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章