1. 程式人生 > 實用技巧 >Lombok:讓JAVA程式碼更優雅

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 {
private final String name;
private int age;
private double score;
private String[] tags;
}

我們往往需要定義一系列的Get和Set方法最終展示形式如:

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

那我們有沒有可以簡化的辦法呢,第一種就是使用IDEA等IDE提供的一鍵生成的快捷鍵,第二種就是我們今天介紹的 Lombok專案:

@Data 
public class DataExample {
private final String name;
@Setter(AccessLevel.PACKAGE)
private int age;
private double score;
private String[] tags;
}

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() {
val example = new ArrayList<String>();
example.add("Hello, World!");
val foo = example.get(0);
return foo.toLowerCase();
}

翻譯成 Java 程式是:

public String example() {
final ArrayList<String> example = new ArrayList<String>();
example.add("Hello, World!");
final String foo = example.get(0);
return foo.toLowerCase();
}

作者注:也就是型別推導啦。

@NonNull

Null 即是罪惡

public class NonNullExample extends Something {
private String name;

public NonNullExample(@NonNull Person person) {
super("Hello");
this.name = person.getName();
}
}

翻譯成 Java 程式是:

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

@Cleanup

自動化才是生產力

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

翻譯成 Java 程式是:

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

作者注: JKD7裡面就已經提供 try with resource

@Getter/@Setter

再也不寫public int getFoo() {return foo;}

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

翻譯成 Java 程式是:

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

@ToString

Debug Log 最強幫手

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

翻譯後:

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) + ")";
}
}

作者注:其實和 org.apache.commons.lang3.builder.ReflectionToStringBuilder 很像。

@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor

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

翻譯後:

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() {
}
}
}

@Data

這個就相當的簡單啦,因為我們發現@ToString,@EqualsAndHashCode,@Getter都很常用,這個一個註解就相當於

@ToString
@EqualsAndHashCode
@Getter(所有欄位)
@Setter (所有非final欄位)
@RequiredArgsConstructor

@Value

@Value public class ValueExample {
String name;
@Wither(AccessLevel.PACKAGE) @NonFinal int age;
double score;
protected String[] tags;

@ToString(includeFieldNames=true)
@Value(staticConstructor="of")
public static class Exercise<T> {
String name;
T value;
}
}

翻譯後:

public final class ValueExample {
private final String name;
private int age;
private final double score;
protected final String[] tags;

@java.beans.ConstructorProperties({"name", "age", "score", "tags"})
public ValueExample(String name, int age, double score, String[] tags) {
this.name = name;
this.age = age;
this.score = score;
this.tags = tags;
}

public String getName() {
return this.name;
}

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

public double getScore() {
return this.score;
}

public String[] getTags() {
return this.tags;
}

@java.lang.Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof ValueExample)) return false;
final ValueExample other = (ValueExample)o;
final Object this$name = this.getName();
final Object other$name = other.getName();
if (this$name == null ? other$name != null : !this$name.equals(other$name)) 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;
}

@java.lang.Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
result = result * PRIME + this.getAge();
final long $score = Double.doubleToLongBits(this.getScore());
result = result * PRIME + (int)($score >>> 32 ^ $score);
result = result * PRIME + Arrays.deepHashCode(this.getTags());
return result;
}

@java.lang.Override
public String toString() {
return "ValueExample(name=" + getName() + ", age=" + getAge() + ", score=" + getScore() + ", tags=" + Arrays.deepToString(getTags()) + ")";
}

ValueExample withAge(int age) {
return this.age == age ? this : new ValueExample(name, age, score, tags);
}

public static final 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;
}

@java.lang.Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof ValueExample.Exercise)) return false;
final Exercise<?> other = (Exercise<?>)o;
final Object this$name = this.getName();
final Object other$name = other.getName();
if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
final Object this$value = this.getValue();
final Object other$value = other.getValue();
if (this$value == null ? other$value != null : !this$value.equals(other$value)) return false;
return true;
}

@java.lang.Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
final Object $value = this.getValue();
result = result * PRIME + ($value == null ? 43 : $value.hashCode());
return result;
}

@java.lang.Override
public String toString() {
return "ValueExample.Exercise(name=" + getName() + ", value=" + getValue() + ")";
}
}
}

我們發現了 @Value 就是 @Data 的不可變版本。至於不可變有什麼好處。可有參看此篇(https://blogs.msdn.microsoft.com/ericlippert/2007/11/13/immutability-in-c-part-one-kinds-of-immutability/)

@Builder

我的最愛

@Builder
public class BuilderExample {
private String name;
private int age;
@Singular private Set<String> occupations;
}
翻譯後:

public class BuilderExample {
private String name;
private int age;
private Set<String> occupations;

BuilderExample(String name, int age, Set<String> occupations) {
this.name = name;
this.age = age;
this.occupations = occupations;
}

public static BuilderExampleBuilder builder() {
return new BuilderExampleBuilder();
}

public static class BuilderExampleBuilder {
private String name;
private int age;
private java.util.ArrayList<String> occupations;

BuilderExampleBuilder() {
}

public BuilderExampleBuilder name(String name) {
this.name = name;
return this;
}

public BuilderExampleBuilder age(int age) {
this.age = age;
return this;
}

public BuilderExampleBuilder occupation(String occupation) {
if (this.occupations == null) {
this.occupations = new java.util.ArrayList<String>();
}

this.occupations.add(occupation);
return this;
}

public BuilderExampleBuilder occupations(Collection<? extends String> occupations) {
if (this.occupations == null) {
this.occupations = new java.util.ArrayList<String>();
}

this.occupations.addAll(occupations);
return this;
}

public BuilderExampleBuilder clearOccupations() {
if (this.occupations != null) {
this.occupations.clear();
}

return this;
}

public BuilderExample build() {
// complicated switch statement to produce a compact properly sized immutable set omitted.
// go to https://projectlombok.org/features/Singular-snippet.html to see it.
Set<String> occupations = ...;
return new BuilderExample(name, age, occupations);
}

@java.lang.Override
public String toString() {
return "BuilderExample.BuilderExampleBuilder(name = " + this.name + ", age = " + this.age + ", occupations = " + this.occupations + ")";
}
}
}

builder是現在比較推崇的一種構建值物件的方式。

作者注:生成器模式

@SneakyThrows

to RuntimeException 小助手

public class SneakyThrowsExample implements Runnable {
@SneakyThrows(UnsupportedEncodingException.class)
public String utf8ToString(byte[] bytes) {
return new String(bytes, "UTF-8");
}

@SneakyThrows
public void run() {
throw new Throwable();
}
}

翻譯後

public class SneakyThrowsExample implements Runnable {
public String utf8ToString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw Lombok.sneakyThrow(e);
}
}

public void run() {
try {
throw new Throwable();
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
}

很好的隱藏了異常,有時候的確會有這樣的煩惱,從某種程度上也是遵循的了 let is crash

@Synchronized

public class SynchronizedExample {
private final Object readLock = new Object();

@Synchronized
public static void hello() {
System.out.println("world");
}

@Synchronized
public int answerToLife() {
return 42;
}

@Synchronized("readLock")
public void foo() {
System.out.println("bar");
}
}

翻譯後

public class SynchronizedExample {
private static final Object $LOCK = new Object[0];
private final Object $lock = new Object[0];
private final Object readLock = new Object();

public static void hello() {
synchronized($LOCK) {
System.out.println("world");
}
}

public int answerToLife() {
synchronized($lock) {
return 42;
}
}

public void foo() {
synchronized(readLock) {
System.out.println("bar");
}
}
}

這個就比較簡單直接添加了synchronized關鍵字就Ok啦。不過現在JDK也比較推薦的是 Lock 物件,這個可能用的不是特別多。

@Getter(lazy=true)

節約是美德

public class GetterLazyExample {
@Getter(lazy=true) private final double[] cached = expensive();

private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}

翻譯後:

public class GetterLazyExample {
private final java.util.concurrent.AtomicReference<java.lang.Object> cached = new java.util.concurrent.AtomicReference<java.lang.Object>();

public double[] getCached() {
java.lang.Object value = this.cached.get();
if (value == null) {
synchronized(this.cached) {
value = this.cached.get();
if (value == null) {
final double[] actualValue = expensive();
value = actualValue == null ? this.cached : actualValue;
this.cached.set(value);
}
}
}
return (double[])(value == this.cached ? null : value);
}

private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}

@Log

再也不用寫那些差不多的LOG啦

@Log
public class LogExample {

public static void main(String... args) {
log.error("Something's wrong here");
}
}
@Slf4j
public class LogExampleOther {

public static void main(String... args) {
log.error("Something else is wrong here");
}
}
@CommonsLog(topic="CounterLog")
public class LogExampleCategory {

public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
}

翻譯後:

public class LogExample {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());

public static void main(String... args) {
log.error("Something's wrong here");
}
}
public class LogExampleOther {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class);

public static void main(String... args) {
log.error("Something else is wrong here");
}
}
public class LogExampleCategory {
private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog");

public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
}

Lombok原理

說道 Lombok,我們就得去提到 JSR 269: Pluggable Annotation Processing API (https://www.jcp.org/en/jsr/detail?id=269) 。JSR 269 之前我們也有註解這樣的神器,可是我們比如想要做什麼必須使用反射,反射的方法侷限性較大。首先,它必須定義@Retention為RetentionPolicy.RUNTIME,只能在執行時通過反射來獲取註解值,使得執行時程式碼效率降低。其次,如果想在編譯階段利用註解來進行一些檢查,對使用者的某些不合理程式碼給出錯誤報告,反射的使用方法就無能為力了。而 JSR 269 之後我們可以在 Javac的編譯期利用註解做這些事情。所以我們發現核心的區分是在 執行期 還是 編譯期。

從上圖可知,Annotation Processing 是在解析和生成之間的一個步驟。

上圖是 Lombok 處理流程,在Javac 解析成抽象語法樹之後(AST), Lombok 根據自己的註解處理器,動態的修改 AST,增加新的節點(所謂程式碼),最終通過分析和生成位元組碼。

關於原理我們大致上的描述下,如果有興趣可以參考下方文件。