Lombok:讓JAVA程式碼更優雅
關於Lombok,其實在網上可以找到很多如何使用的文章,但是很少能找到比較齊全的整理。我也一直尋思著想寫一篇各個註解用法的總結,但是一直都沒有付諸行動。今天看到了微信公眾號”原力注入”推送的這篇文章,總結的內容很全,所以分享給所有關注我部落格的朋友們。
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.
如Github上專案介紹所言,Lombok專案通過新增“處理程式”,使java成為一種更為簡單的語言。作為一個Old Java Developer,我們都知道我們經常需要定義一系列的套路,比如定義如下的格式物件。
public class DataExample {
|
我們往往需要定義一系列的Get和Set方法最終展示形式如:
public class DataExample {
|
那我們有沒有可以簡化的辦法呢,第一種就是使用IDEA等IDE提供的一鍵生成的快捷鍵,第二種就是我們今天介紹的 Lombok專案:
|
Wow…這樣就可以完成我們的需求,簡直是太棒了,僅僅需要幾個註解,我們就擁有了完整的GetSet方法,還包含了ToString等方法的生成。
Lombok安裝
整個Lombok只有一個Jar包,可到這裡下載:https://projectlombok.org/download
Lombok支援多種使用安裝方式,這裡我們講最常見的對兩大IDE的支援:
Eclipse (含延伸版本)
雙擊開啟 lombok.jar (前提:你得裝了JDK), 可見如下頁面點選 Install/Update:
恭喜你,已經安裝成功了。我們開啟 Eclipse 的 About 頁面我們可以看見。
IntelliJ IDEA
- 定位到 File > Settings > Plugins
- 點選 Browse repositories…
- 搜尋 Lombok Plugin
- 點選 Install plugin
- 重啟 IDEA
更多安裝請參考:https://projectlombok.org/
Lombok使用
Lombok 其實也不能算是一個特別新的專案,從 2011 開始在中心倉庫提供支援,現在也分為 stable 和 experimental 兩個版本,本文側重介紹 stable 功能:
val
如果對其他的語言有研究的會發現,很多語言是使用 var 作為變數申明,val作為常量申明。這裡的val也是這個作用。
public String example() {
|
翻譯成 Java 程式是:
public String example() {
|
作者注:也就是型別推導啦。
@NonNull
Null 即是罪惡
public class NonNullExample extends Something {
|
翻譯成 Java 程式是:
public class NonNullExample extends Something {
|
@Cleanup
自動化才是生產力
public class CleanupExample {
|
翻譯成 Java 程式是:
public class CleanupExample {
|
作者注: JKD7裡面就已經提供 try with resource
@Getter/@Setter
再也不寫public int getFoo() {return foo;}
public class GetterSetterExample {
|
翻譯成 Java 程式是:
public class GetterSetterExample {
|
@ToString
Debug Log 最強幫手
|
翻譯後:
public class ToStringExample {
|
作者注:其實和 org.apache.commons.lang3.builder.ReflectionToStringBuilder 很像。
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
|
翻譯後:
public class ConstructorExample<T> {
|
@Data
這個就相當的簡單啦,因為我們發現@ToString
,@EqualsAndHashCode
,@Getter
都很常用,這個一個註解就相當於
|
@Value
|
翻譯後:
public final class ValueExample { |