欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java Lombok簡介、使用、工作原理、優(yōu)缺點

 更新時間:2021年03月02日 10:13:56   作者:雙鬼帶單  
這篇文章主要介紹了Java Lombok簡介、使用、工作原理、優(yōu)缺點的相關(guān)資料,幫助大家更好的理解和學(xué)習使用Java Lombok,感興趣的朋友可以了解下

簡介

官方介紹

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully featured builder, automate your logging variables, and much more.

翻譯之后就是:

Lombok 項目是一個 Java 庫,它會自動插入您的編輯器和構(gòu)建工具中,簡化您的 Java 。 不需要再寫另一個 getter、setter、toString 或 equals 方法,帶有一個注釋的您的類有一個功能全面的生成器,可以自動化您的日志記錄變量,以及更多其他功能

官網(wǎng)鏈接

使用

添加maven依賴

<dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
 <version>1.18.16</version>
 <scope>provided</scope>
</dependency>

注意: 在這里 scope 要設(shè)置為 provided, 防止依賴傳遞給其他項目

安裝插件(可選)

在開發(fā)過程中,一般還需要配合插件使用,在 IDEA 中需要安裝 Lombok 插件即可

為什么要安裝插件?

首先在不安裝插件的情況下,代碼是可以正常的編譯和運行的。如果不安裝插件,IDEA 不會自動提示 Lombok 在編譯時才會生成的一些樣板方法,同樣 IDEA 在校驗語法正確性的時候也會提示有問題,會有大面積報紅的代碼

示例

下面舉兩個栗子,看看使用 lombok 和不使用的區(qū)別

創(chuàng)建一個用戶類

不使用 Lombok

public class User {
 private Integer id;
 private Integer age;
 private String realName;

 public User() {
 }

 @Override
 public boolean equals(Object o) {
 if (this == o) {
  return true;
 }
 if (o == null || getClass() != o.getClass()) {
  return false;
 }

 User user = (User) o;

 if (!Objects.equals(id, user.id)) {
  return false;
 }
 if (!Objects.equals(age, user.age)) {
  return false;
 }
 return Objects.equals(realName, user.realName);
 }

 @Override
 public int hashCode() {
 int result = id != null ? id.hashCode() : 0;
 result = 31 * result + (age != null ? age.hashCode() : 0);
 result = 31 * result + (realName != null ? realName.hashCode() : 0);
 return result;
 }

 @Override
 public String toString() {
 return "User{" +
  "id=" + id +
  ", age=" + age +
  ", realName='" + realName + '\'' +
  '}';
 }

 public Integer getId() {
 return id;
 }

 public void setId(Integer id) {
 this.id = id;
 }

 public Integer getAge() {
 return age;
 }

 public void setAge(Integer age) {
 this.age = age;
 }

 public String getRealName() {
 return realName;
 }

 public void setRealName(String realName) {
 this.realName = realName;
 }
}

使用Lombok

@Data
public class User {
 private Integer id;
 private String username;
 private Integer age;
}

使用 @Data 注解會在編譯的時候自動生成以下模板代碼:

  • toString
  • equals
  • hashCode
  • getter 不會對 final 屬性生成
  • setter 不會對 final 屬性生成
  • 必要參數(shù)的構(gòu)造器

關(guān)于什么是必要參數(shù)下面會舉例說明

全部注解

上面已經(jīng)簡單看了一下 @Data 注解,下面看下所有的可以用的注解

@NonNull 注解在字段和構(gòu)造器的參數(shù)上。注解在字段上,則在 setter, constructor 方法中加入判空,注意這里需要配合 @Setter、@RequiredArgsConstructor、@AllArgsConstructor 使用;注解在構(gòu)造器方法參數(shù)上,則在構(gòu)造的時候加入判空
@Cleanup 注解在本地變量上。負責清理資源,當方法直接結(jié)束時,會調(diào)用 close 方法
@Setter 注解在類或字段。注解在類時為所有字段生成setter方法,注解在字段上時只為該字段生成setter方法,同時可以指定生成的 setter 方法的訪問級別
@Getter 使用方法同 @Setter,區(qū)別在于生成的是 getter 方法
@ToString 注解在類上。添加toString方法
@EqualsAndHashCode 注解在類。生成hashCode和equals方法
@NoArgsConstructor 注解在類。生成無參的構(gòu)造方法。
@RequiredArgsConstructor 注解在類。為類中需要特殊處理的字段生成構(gòu)造方法,比如 final 和被 @NonNull 注解的字段。
@AllArgsConstructor 注解在類,生成包含類中所有字段的構(gòu)造方法。
@Data 注解在類,生成setter/getter、equals、canEqual、hashCode、toString方法,如為final屬性,則不會為該屬性生成setter方法。
@Value 注解在類和屬性上。如果注解在類上在類實例創(chuàng)建后不可修改,即不會生成 setter 方法,這個會導(dǎo)致 @Setter 不起作用
@Builder 注解在類上,生成構(gòu)造器
@SneakyThrows
@Synchronized 注解在方法上,生成同步方法
@With
日志相關(guān): 注解在類,生成 log 常量,類似 private static final xxx log

  • @Log java.util.logging.Logger
  • @CommonsLog org.apache.commons.logging.Log
  • @Flogger com.google.common.flogger.FluentLogger
  • @JBossLog org.jboss.logging.Logger
  • @Log4j org.apache.log4j.Logger
  • @Log4j2 org.apache.logging.log4j.Logger
  • @Slf4j org.slf4j.Logger
  • @XSlf4j org.slf4j.ext.XLogger

關(guān)于所有的注解可以查看 https://projectlombok.org/features/all

綜合實例

綜合實例一

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Getter      // 生成 getter
@AllArgsConstructor   // 生成所有的參數(shù)
@RequiredArgsConstructor // 生成必要參數(shù)的構(gòu)造器
@ToString   // 生成 toString
@EqualsAndHashCode // 生成 equals 和 hashCode
@Builder   // 生成一個 builder
public class UserLombok {

 // 創(chuàng)建 setter 并且校驗 id 不能為空
 @Setter
 @NonNull
 private Integer id;

 // 創(chuàng)建 setter 且生成方法的訪問級別為 PROTECTED
 @Setter(AccessLevel.PROTECTED)
 private Integer age;

 // 創(chuàng)建 setter 不校驗是否為空
 @Setter
 private String realName;

 // 構(gòu)造器,校驗 id 不能為空
 public UserLombok(@NonNull Integer id, Integer age) {
 this.id = id;
 this.age = age;
 }

 /**
 * 自定義 realName 的 setter 方法,這個優(yōu)先高于 Lombok
 * @param realName 真實姓名
 */
 public void setRealName(String realName) {
 this.realName = "realName:" + realName;
 }
}

具體生成的類為

import lombok.NonNull;

public class UserLombok {
 @NonNull
 private Integer id;
 private Integer age;
 private String realName;

 public UserLombok(@NonNull Integer id, Integer age) {
 if (id == null) {
  throw new NullPointerException("id is marked non-null but is null");
 } else {
  this.id = id;
  this.age = age;
 }
 }

 public void setRealName(String realName) {
 this.realName = "realName:" + realName;
 }

 public static UserLombok.UserLombokBuilder builder() {
 return new UserLombok.UserLombokBuilder();
 }

 @NonNull
 public Integer getId() {
 return this.id;
 }

 public Integer getAge() {
 return this.age;
 }

 public String getRealName() {
 return this.realName;
 }

 public UserLombok(@NonNull Integer id, Integer age, String realName) {
 if (id == null) {
  throw new NullPointerException("id is marked non-null but is null");
 } else {
  this.id = id;
  this.age = age;
  this.realName = realName;
 }
 }

 public UserLombok(@NonNull Integer id) {
 if (id == null) {
  throw new NullPointerException("id is marked non-null but is null");
 } else {
  this.id = id;
 }
 }

 public String toString() {
 return "UserLombok(id=" + this.getId() + ", age=" + this.getAge() + ", realName=" + this.getRealName() + ")";
 }

 public boolean equals(Object o) {
 if (o == this) {
  return true;
 } else if (!(o instanceof UserLombok)) {
  return false;
 } else {
  UserLombok other = (UserLombok)o;
  if (!other.canEqual(this)) {
  return false;
  } else {
  label47: {
   Object this$id = this.getId();
   Object other$id = other.getId();
   if (this$id == null) {
   if (other$id == null) {
    break label47;
   }
   } else if (this$id.equals(other$id)) {
   break label47;
   }

   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;
  }

  Object this$realName = this.getRealName();
  Object other$realName = other.getRealName();
  if (this$realName == null) {
   if (other$realName != null) {
   return false;
   }
  } else if (!this$realName.equals(other$realName)) {
   return false;
  }

  return true;
  }
 }
 }

 protected boolean canEqual(Object other) {
 return other instanceof UserLombok;
 }

 public int hashCode() {
 int PRIME = true;
 int result = 1;
 Object $id = this.getId();
 int result = result * 59 + ($id == null ? 43 : $id.hashCode());
 Object $age = this.getAge();
 result = result * 59 + ($age == null ? 43 : $age.hashCode());
 Object $realName = this.getRealName();
 result = result * 59 + ($realName == null ? 43 : $realName.hashCode());
 return result;
 }

 public void setId(@NonNull Integer id) {
 if (id == null) {
  throw new NullPointerException("id is marked non-null but is null");
 } else {
  this.id = id;
 }
 }

 protected void setAge(Integer age) {
 this.age = age;
 }

 public static class UserLombokBuilder {
 private Integer id;
 private Integer age;
 private String realName;

 UserLombokBuilder() {
 }

 public UserLombok.UserLombokBuilder id(@NonNull Integer id) {
  if (id == null) {
  throw new NullPointerException("id is marked non-null but is null");
  } else {
  this.id = id;
  return this;
  }
 }

 public UserLombok.UserLombokBuilder age(Integer age) {
  this.age = age;
  return this;
 }

 public UserLombok.UserLombokBuilder realName(String realName) {
  this.realName = realName;
  return this;
 }

 public UserLombok build() {
  return new UserLombok(this.id, this.age, this.realName);
 }

 public String toString() {
  return "UserLombok.UserLombokBuilder(id=" + this.id + ", age=" + this.age + ", realName=" + this.realName + ")";
 }
 }
}

綜合實例二

@Value
public class UserLombok {

 @NonNull
 private Integer id;

 // 這里的 setter 不會生成,所有沒用,這里反面示例
 @Setter(AccessLevel.PROTECTED)
 private Integer age;

 private String realName;

}

@ValueToString、EqualsAndHashCode、AllArgsConstructor、Getter 的組合注解

生成的代碼

import lombok.NonNull;

public final class UserLombok {
 @NonNull
 private final Integer id;
 private final Integer age;
 private final String realName;

 public UserLombok(@NonNull Integer id, Integer age, String realName) {
 if (id == null) {
  throw new NullPointerException("id is marked non-null but is null");
 } else {
  this.id = id;
  this.age = age;
  this.realName = realName;
 }
 }

 @NonNull
 public Integer getId() {
 return this.id;
 }

 public Integer getAge() {
 return this.age;
 }

 public String getRealName() {
 return this.realName;
 }

 public boolean equals(Object o) {
 if (o == this) {
  return true;
 } else if (!(o instanceof UserLombok)) {
  return false;
 } else {
  UserLombok other;
  label44: {
  other = (UserLombok)o;
  Object this$id = this.getId();
  Object other$id = other.getId();
  if (this$id == null) {
   if (other$id == null) {
   break label44;
   }
  } else if (this$id.equals(other$id)) {
   break label44;
  }

  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;
  }

  Object this$realName = this.getRealName();
  Object other$realName = other.getRealName();
  if (this$realName == null) {
  if (other$realName != null) {
   return false;
  }
  } else if (!this$realName.equals(other$realName)) {
  return false;
  }

  return true;
 }
 }

 public int hashCode() {
 int PRIME = true;
 int result = 1;
 Object $id = this.getId();
 int result = result * 59 + ($id == null ? 43 : $id.hashCode());
 Object $age = this.getAge();
 result = result * 59 + ($age == null ? 43 : $age.hashCode());
 Object $realName = this.getRealName();
 result = result * 59 + ($realName == null ? 43 : $realName.hashCode());
 return result;
 }

 public String toString() {
 return "UserLombok(id=" + this.getId() + ", age=" + this.getAge() + ", realName=" + this.getRealName() + ")";
 }
}

綜合實例三

日志使用

import lombok.extern.java.Log;

@Log
public class LogLombok {

 public void log() {
 log.info("打個日志");
 }
}

生成后代碼

import java.util.logging.Logger;

public class LogLombok {
 private static final Logger log = Logger.getLogger(LogLombok.class.getName());

 public LogLombok() {
 }

 public void log() {
 log.info("打個日志");
 }
}

通過上面的示例,我們可以看出 Lombok 可以大大簡化我們的代碼

Lombok的優(yōu)缺點

  • 優(yōu)點:

提高開發(fā)效率,自動生成getter/setter、toString、builder 等,尤其是類不斷改變過程中,如果使用 IDEA 自動生成的代碼,我們則需要不停的刪除、重新生成,使用 Lombok 則自動幫助我們完成
讓代碼變得簡潔,不用過多的去關(guān)注相應(yīng)的模板方法,其中 getter/setter、toString、builder 均為模板代碼,寫著難受,不寫還不行,而且在 java 14 已經(jīng)開始計劃支持 record, 也在幫我們從原生方面解決這種模板代碼
屬性做修改時,也簡化了維護為這些屬性所生成的getter/setter方法等

  • 缺點:

不同開發(fā)人員同時開發(fā)同一個使用 Lombok 項目、需要安裝 Lombok 插件
不利于重構(gòu)屬性名稱,對應(yīng)的 setter、getter、builder, IDEA 無法幫助自動重構(gòu)
有可能降低了源代碼的可讀性和完整性,降低了閱讀源代碼的舒適度,誰會去閱讀模板代碼呢

解決編譯時出錯問題

編譯時出錯,可能是沒有啟用注解處理器。Build, Execution, Deployment > Annotation Processors > Enable annotation processing。設(shè)置完成之后程序正常運行。

避坑指南

  • 盡量不要使用 @Data 注解, 這個注解太全了,不利于維護,除非你知道你在干什么
  • Java 默認機制如果有其他構(gòu)造器,則不會生成無參構(gòu)造器,在使用 @AllArgsConstructor 注解時,記得加上 @NoArgsConstructor
  • 如果類定義還在變化階段,不建議使用 @AllArgsConstructor 注解
  • @Setter、@Getter 注解如果需要可以縮小使用范圍
  • @ToString 注解默認不會生成父類的信息,如果需要生成需要 @ToString(callSuper = true)
  • @RequiredArgsConstructor@NoArgsConstructor 盡量不要一起使用,無參構(gòu)造器無法處理 @NonNull,但在序列化/反序列化的還是需要提供無參的
  • 當團隊決定不再使用 Lombok 的時候,可以使用 Lombok 插件的 Delombok 一鍵去除,在 Refactor > Delombok

再次注意- @AllArgsConstructor 盡量不要使用

參考

https://projectlombok.org
https://github.com/rzwitserloot/lombok

Lombok工作原理

工作原理來自網(wǎng)上資料

在Lombok使用的過程中,只需要添加相應(yīng)的注解,無需再為此寫任何代碼。自動生成的代碼到底是如何產(chǎn)生的呢?

核心之處就是對于注解的解析上。JDK5引入了注解的同時,也提供了兩種解析方式。

  • 運行時解析

運行時能夠解析的注解,必須將@Retention設(shè)置為RUNTIME,這樣就可以通過反射拿到該注解。java.lang.reflect反射包中提供了一個接口AnnotatedElement,該接口定義了獲取注解信息的幾個方法,Class、Constructor、Field、Method、Package等都實現(xiàn)了該接口,對反射熟悉的朋友應(yīng)該都會很熟悉這種解析方式。

  • 編譯時解析

編譯時解析有兩種機制,分別簡單描述下:

1)Annotation Processing Tool

apt自JDK5產(chǎn)生,JDK7已標記為過期,不推薦使用,JDK8中已徹底刪除,自JDK6開始,可以使用Pluggable Annotation Processing API來替換它,apt被替換主要有2點原因:

  • api都在com.sun.mirror非標準包下
  • 沒有集成到j(luò)avac中,需要額外運行

2)Pluggable Annotation Processing API

JSR 269自JDK6加入,作為apt的替代方案,它解決了apt的兩個問題,javac在執(zhí)行的時候會調(diào)用實現(xiàn)了該API的程序,這樣我們就可以對編譯器做一些增強,javac執(zhí)行的過程如下:

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

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

通過讀Lombok源碼,發(fā)現(xiàn)對應(yīng)注解的實現(xiàn)都在HandleXXX中,比如@Getter注解的實現(xiàn)在HandleGetter.handle()。還有一些其它類庫使用這種方式實現(xiàn),比如Google Auto、Dagger等等。

以上就是Java Lombok簡介、使用、工作原理、優(yōu)缺點的詳細內(nèi)容,更多關(guān)于Java Lombok的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論