Java Lombok簡(jiǎn)介、使用、工作原理、優(yōu)缺點(diǎn)
官方介紹
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 項(xiàng)目是一個(gè) Java 庫(kù),它會(huì)自動(dòng)插入您的編輯器和構(gòu)建工具中,簡(jiǎn)化您的 Java 。 不需要再寫(xiě)另一個(gè) getter、setter、toString 或 equals 方法,帶有一個(gè)注釋的您的類(lèi)有一個(gè)功能全面的生成器,可以自動(dòng)化您的日志記錄變量,以及更多其他功能
官網(wǎng)鏈接
使用添加maven依賴<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> <scope>provided</scope></dependency>
注意: 在這里 scope 要設(shè)置為 provided, 防止依賴傳遞給其他項(xiàng)目
安裝插件(可選)在開(kāi)發(fā)過(guò)程中,一般還需要配合插件使用,在 IDEA 中需要安裝 Lombok 插件即可
為什么要安裝插件?
首先在不安裝插件的情況下,代碼是可以正常的編譯和運(yùn)行的。如果不安裝插件,IDEA 不會(huì)自動(dòng)提示 Lombok 在編譯時(shí)才會(huì)生成的一些樣板方法,同樣 IDEA 在校驗(yàn)語(yǔ)法正確性的時(shí)候也會(huì)提示有問(wèn)題,會(huì)有大面積報(bào)紅的代碼
示例下面舉兩個(gè)栗子,看看使用 lombok 和不使用的區(qū)別
創(chuàng)建一個(gè)用戶類(lèi)
不使用 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
@Datapublic class User { private Integer id; private String username; private Integer age;}
使用 @Data 注解會(huì)在編譯的時(shí)候自動(dòng)生成以下模板代碼:
toString equals hashCode getter 不會(huì)對(duì) final 屬性生成 setter 不會(huì)對(duì) final 屬性生成 必要參數(shù)的構(gòu)造器關(guān)于什么是必要參數(shù)下面會(huì)舉例說(shuō)明
全部注解上面已經(jīng)簡(jiǎn)單看了一下 @Data 注解,下面看下所有的可以用的注解
@NonNull 注解在字段和構(gòu)造器的參數(shù)上。注解在字段上,則在 setter, constructor 方法中加入判空,注意這里需要配合 @Setter、@RequiredArgsConstructor、@AllArgsConstructor 使用;注解在構(gòu)造器方法參數(shù)上,則在構(gòu)造的時(shí)候加入判空@Cleanup 注解在本地變量上。負(fù)責(zé)清理資源,當(dāng)方法直接結(jié)束時(shí),會(huì)調(diào)用 close 方法@Setter 注解在類(lèi)或字段。注解在類(lèi)時(shí)為所有字段生成setter方法,注解在字段上時(shí)只為該字段生成setter方法,同時(shí)可以指定生成的 setter 方法的訪問(wèn)級(jí)別@Getter 使用方法同 @Setter,區(qū)別在于生成的是 getter 方法@ToString 注解在類(lèi)上。添加toString方法@EqualsAndHashCode 注解在類(lèi)。生成hashCode和equals方法@NoArgsConstructor 注解在類(lèi)。生成無(wú)參的構(gòu)造方法。@RequiredArgsConstructor 注解在類(lèi)。為類(lèi)中需要特殊處理的字段生成構(gòu)造方法,比如 final 和被 @NonNull 注解的字段。@AllArgsConstructor 注解在類(lèi),生成包含類(lèi)中所有字段的構(gòu)造方法。@Data 注解在類(lèi),生成setter/getter、equals、canEqual、hashCode、toString方法,如為final屬性,則不會(huì)為該屬性生成setter方法。@Value 注解在類(lèi)和屬性上。如果注解在類(lèi)上在類(lèi)實(shí)例創(chuàng)建后不可修改,即不會(huì)生成 setter 方法,這個(gè)會(huì)導(dǎo)致 @Setter 不起作用@Builder 注解在類(lèi)上,生成構(gòu)造器@SneakyThrows@Synchronized 注解在方法上,生成同步方法@With日志相關(guān): 注解在類(lèi),生成 log 常量,類(lèi)似 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
綜合實(shí)例綜合實(shí)例一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 // 生成一個(gè) builderpublic class UserLombok { // 創(chuàng)建 setter 并且校驗(yàn) id 不能為空 @Setter @NonNull private Integer id; // 創(chuàng)建 setter 且生成方法的訪問(wèn)級(jí)別為 PROTECTED @Setter(AccessLevel.PROTECTED) private Integer age; // 創(chuàng)建 setter 不校驗(yàn)是否為空 @Setter private String realName; // 構(gòu)造器,校驗(yàn) id 不能為空 public UserLombok(@NonNull Integer id, Integer age) { this.id = id; this.age = age; } /** * 自定義 realName 的 setter 方法,這個(gè)優(yōu)先高于 Lombok * @param realName 真實(shí)姓名 */ public void setRealName(String realName) { this.realName = 'realName:' + realName; }}
具體生成的類(lèi)為
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 + ')'; } }}綜合實(shí)例二
@Valuepublic class UserLombok { @NonNull private Integer id; // 這里的 setter 不會(huì)生成,所有沒(méi)用,這里反面示例 @Setter(AccessLevel.PROTECTED) private Integer age; private String realName;}
@Value 是 ToString、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() + ')'; }}綜合實(shí)例三
日志使用
import lombok.extern.java.Log;@Logpublic class LogLombok { public void log() { log.info('打個(gè)日志'); }}
生成后代碼
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('打個(gè)日志'); }}
通過(guò)上面的示例,我們可以看出 Lombok 可以大大簡(jiǎn)化我們的代碼
Lombok的優(yōu)缺點(diǎn) 優(yōu)點(diǎn):提高開(kāi)發(fā)效率,自動(dòng)生成getter/setter、toString、builder 等,尤其是類(lèi)不斷改變過(guò)程中,如果使用 IDEA 自動(dòng)生成的代碼,我們則需要不停的刪除、重新生成,使用 Lombok 則自動(dòng)幫助我們完成讓代碼變得簡(jiǎn)潔,不用過(guò)多的去關(guān)注相應(yīng)的模板方法,其中 getter/setter、toString、builder 均為模板代碼,寫(xiě)著難受,不寫(xiě)還不行,而且在 java 14 已經(jīng)開(kāi)始計(jì)劃支持 record, 也在幫我們從原生方面解決這種模板代碼屬性做修改時(shí),也簡(jiǎn)化了維護(hù)為這些屬性所生成的getter/setter方法等
缺點(diǎn):不同開(kāi)發(fā)人員同時(shí)開(kāi)發(fā)同一個(gè)使用 Lombok 項(xiàng)目、需要安裝 Lombok 插件不利于重構(gòu)屬性名稱,對(duì)應(yīng)的 setter、getter、builder, IDEA 無(wú)法幫助自動(dòng)重構(gòu)有可能降低了源代碼的可讀性和完整性,降低了閱讀源代碼的舒適度,誰(shuí)會(huì)去閱讀模板代碼呢
解決編譯時(shí)出錯(cuò)問(wèn)題編譯時(shí)出錯(cuò),可能是沒(méi)有啟用注解處理器。Build, Execution, Deployment > Annotation Processors > Enable annotation processing。設(shè)置完成之后程序正常運(yùn)行。
避坑指南 盡量不要使用 @Data 注解, 這個(gè)注解太全了,不利于維護(hù),除非你知道你在干什么 Java 默認(rèn)機(jī)制如果有其他構(gòu)造器,則不會(huì)生成無(wú)參構(gòu)造器,在使用 @AllArgsConstructor 注解時(shí),記得加上 @NoArgsConstructor 如果類(lèi)定義還在變化階段,不建議使用 @AllArgsConstructor 注解 @Setter、@Getter 注解如果需要可以縮小使用范圍 @ToString 注解默認(rèn)不會(huì)生成父類(lèi)的信息,如果需要生成需要 @ToString(callSuper = true) @RequiredArgsConstructor 和 @NoArgsConstructor 盡量不要一起使用,無(wú)參構(gòu)造器無(wú)法處理 @NonNull,但在序列化/反序列化的還是需要提供無(wú)參的 當(dāng)團(tuán)隊(duì)決定不再使用 Lombok 的時(shí)候,可以使用 Lombok 插件的 Delombok 一鍵去除,在 Refactor > Delombok 中再次注意- @AllArgsConstructor 盡量不要使用
參考https://projectlombok.orghttps://github.com/rzwitserloot/lombok
Lombok工作原理工作原理來(lái)自網(wǎng)上資料
在Lombok使用的過(guò)程中,只需要添加相應(yīng)的注解,無(wú)需再為此寫(xiě)任何代碼。自動(dòng)生成的代碼到底是如何產(chǎn)生的呢?
核心之處就是對(duì)于注解的解析上。JDK5引入了注解的同時(shí),也提供了兩種解析方式。
運(yùn)行時(shí)解析運(yùn)行時(shí)能夠解析的注解,必須將@Retention設(shè)置為RUNTIME,這樣就可以通過(guò)反射拿到該注解。java.lang.reflect反射包中提供了一個(gè)接口AnnotatedElement,該接口定義了獲取注解信息的幾個(gè)方法,Class、Constructor、Field、Method、Package等都實(shí)現(xiàn)了該接口,對(duì)反射熟悉的朋友應(yīng)該都會(huì)很熟悉這種解析方式。
編譯時(shí)解析編譯時(shí)解析有兩種機(jī)制,分別簡(jiǎn)單描述下:
1)Annotation Processing Tool
apt自JDK5產(chǎn)生,JDK7已標(biāo)記為過(guò)期,不推薦使用,JDK8中已徹底刪除,自JDK6開(kāi)始,可以使用Pluggable Annotation Processing API來(lái)替換它,apt被替換主要有2點(diǎn)原因:
api都在com.sun.mirror非標(biāo)準(zhǔn)包下 沒(méi)有集成到j(luò)avac中,需要額外運(yùn)行2)Pluggable Annotation Processing API
JSR 269自JDK6加入,作為apt的替代方案,它解決了apt的兩個(gè)問(wèn)題,javac在執(zhí)行的時(shí)候會(huì)調(diào)用實(shí)現(xiàn)了該API的程序,這樣我們就可以對(duì)編譯器做一些增強(qiáng),javac執(zhí)行的過(guò)程如下:
Lombok本質(zhì)上就是一個(gè)實(shí)現(xiàn)了“JSR 269 API”的程序。在使用javac的過(guò)程中,它產(chǎn)生作用的具體流程如下:
javac對(duì)源代碼進(jìn)行分析,生成了一棵抽象語(yǔ)法樹(shù)(AST) 運(yùn)行過(guò)程中調(diào)用實(shí)現(xiàn)了“JSR 269 API”的Lombok程序 此時(shí)Lombok就對(duì)第一步驟得到的AST進(jìn)行處理,找到@Data注解所在類(lèi)對(duì)應(yīng)的語(yǔ)法樹(shù)(AST),然后修改該語(yǔ)法樹(shù)(AST),增加getter和setter方法定義的相應(yīng)樹(shù)節(jié)點(diǎn) javac使用修改后的抽象語(yǔ)法樹(shù)(AST)生成字節(jié)碼文件,即給class增加新的節(jié)點(diǎn)(代碼塊)通過(guò)讀Lombok源碼,發(fā)現(xiàn)對(duì)應(yīng)注解的實(shí)現(xiàn)都在HandleXXX中,比如@Getter注解的實(shí)現(xiàn)在HandleGetter.handle()。還有一些其它類(lèi)庫(kù)使用這種方式實(shí)現(xiàn),比如Google Auto、Dagger等等。
以上就是Java Lombok簡(jiǎn)介、使用、工作原理、優(yōu)缺點(diǎn)的詳細(xì)內(nèi)容,更多關(guān)于Java Lombok的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼2. VMware中如何安裝Ubuntu3. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)4. phpstudy apache開(kāi)啟ssi使用詳解5. ASP中實(shí)現(xiàn)字符部位類(lèi)似.NET里String對(duì)象的PadLeft和PadRight函數(shù)6. CentOS郵件服務(wù)器搭建系列—— POP / IMAP 服務(wù)器的構(gòu)建( Dovecot )7. django創(chuàng)建css文件夾的具體方法8. asp批量添加修改刪除操作示例代碼9. docker容器調(diào)用yum報(bào)錯(cuò)的解決辦法10. IntelliJ IDEA創(chuàng)建web項(xiàng)目的方法
