文章目錄
1 簡介
Lombok 是一款好用順手的工具,就像 Google Guava 一樣,在此予以強烈推薦,每一個 Java 工程師都應該使用它。Lombok 是一種 Java™ 實用工具,可用來幫助開發人員消除 Java 的冗長代碼,尤其是對於簡單的 Java 對象(POJO),它通過註釋實現這一目的。通過在開發環境中使用 Lombok,開發人員可以節省構建諸如hashCode()
和equals()
這樣的方法以及以往用來分類各種accessor
和mutator
的大量時間。
2 IntelliJ IDEA 安裝 Lombok
通過 IntelliJ IDEA 的插件中心安裝 Lombok 插件:
需要注意的是,在我們使用 Lombok 註解的時候,要將lombok.jar
包導入到工程倉庫,如果是 Maven 項目的話,直接在pom.xml
文件中添加依賴引入即可。
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.8</version>
</dependency>
3 Lombok 用法
3.1 Lombok 註解說明
-
val
:用在局部變量前面,相當於將變量聲明爲final
-
@NonNull
:給方法參數增加這個註解會自動在方法內對該參數進行是否爲空的校驗,如果爲空,則拋出 NPE(NullPointerException
) -
@Cleanup
:自動管理資源,用在局部變量之前,在當前變量範圍內即將執行完畢退出之前會自動清理資源,自動生成try-finally
這樣的代碼來關閉流 -
@Getter/@Setter
:用在屬性上,再也不用自己手寫setter
和getter
方法了,還可以指定訪問範圍 -
@ToString
:用在類上,可以自動覆寫toString
方法,當然還可以加其他參數,例如@ToString(exclude="id")
排除id
屬性,或者@ToString(callSuper=true, includeFieldNames=true)
調用父類的toString
方法,包含所有屬性 -
@EqualsAndHashCode
:用在類上,自動生成equals
方法和hashCode
方法 -
@NoArgsConstructor
、@RequiredArgsConstructor
和@AllArgsConstructor
:用在類上,自動生成無參構造和使用所有參數的構造函數以及把所有@NonNull
屬性作爲參數的構造函數,如果指定staticName = "of"
參數,同時還會生成一個返回類對象的靜態工廠方法,比使用構造函數方便很多 -
@Data
:註解在類上,相當於同時使用了@ToString
、@EqualsAndHashCode
、@Getter
、@Setter
和@RequiredArgsConstrutor
這些註解,對於 POJO 類十分有用 -
@Value
:用在類上,是@Data
的不可變形式,相當於爲屬性添加final
聲明,只提供getter
方法,而不提供setter
方法 -
@Builder
:用在類、構造器、方法上,爲你提供複雜的builder
APIs,讓你可以像如下方式一樣調用Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build()
,更多說明點擊「Builder」參考 -
@SneakyThrows
:自動拋受檢異常,而無需顯式在方法上使用throws
語句 -
@Synchronized
:用在方法上,將方法聲明爲同步的,並自動加鎖,而鎖對象是一個私有的屬性$lock
或$LOCK
,而 Java 中的synchronized
關鍵字鎖對象是this
,鎖在this
或者自己的類對象上存在副作用,就是你不能阻止非受控代碼去鎖this
或者類對象,這可能會導致競爭條件或者其它線程錯誤 -
@Getter(lazy=true)
:可以替代經典的 Double Check Lock 樣板代碼 -
@Log
:根據不同的註解生成不同類型的log
對象,但是實例名稱都是log
,有六種可選實現類@CommonsLog
:Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);
@Log
:Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName());
@Log4j
:Creates log = org.apache.log4j.Logger.getLogger(LogExample.class);
@Log4j2
:Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
@Slf4j
:Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
@XSlf4j
:Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
3.2 Lombok 代碼示例
val
示例:
public static void main(String[] args) {
val sets = new HashSet<String>();
val lists = new ArrayList<String>();
val maps = new HashMap<String, String>();
// 相當於
final Set<String> sets2 = new HashSet<>();
final List<String> lists2 = new ArrayList<>();
final Map<String, String> maps2 = new HashMap<>();
}
@NonNull
示例:
public void notNullExample(@NonNull String string) {
string.length();
}
// 相當於
public void notNullExample(String string) {
if (string != null) {
string.length();
} else {
throw new NullPointerException("null");
}
}
@Cleanup
示例:
public static void main(String[] args) {
try {
@Cleanup InputStream inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 相當於
InputStream inputStream = null;
try {
inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Getter/@Setter
示例:
@Setter(AccessLevel.PUBLIC)
@Getter(AccessLevel.PROTECTED)
private int id;
private String shap;
@ToString
示例:
@ToString(exclude = "id", callSuper = true, includeFieldNames = true)
public class LombokDemo {
private int id;
private String name;
private int age;
public static void main(String[] args) {
//輸出LombokDemo(super=LombokDemo@48524010, name=null, age=0)
System.out.println(new LombokDemo());
}
}
@EqualsAndHashCode
示例:
@EqualsAndHashCode(exclude = {"id", "shape"}, callSuper = false)
public class LombokDemo {
private int id;
private String shap;
}
@NoArgsConstructor
、@RequiredArgsConstructor
和@AllArgsConstructor
示例:
@NoArgsConstructor
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor
public class LombokDemo {
@NonNull
private int id;
@NonNull
private String shap;
private int age;
public static void main(String[] args) {
new LombokDemo(1, "circle");
//使用靜態工廠方法
LombokDemo.of(2, "circle");
//無參構造
new LombokDemo();
//包含所有參數
new LombokDemo(1, "circle", 2);
}
}
@Data
示例:
@Data
public class Menu {
private String shopId;
private String skuMenuId;
private String skuName;
private String normalizeSkuName;
private String dishMenuId;
private String dishName;
private String dishNum;
//默認閾值
private float thresHold = 0;
//新閾值
private float newThresHold = 0;
//總得分
private float totalScore = 0;
}
@Value
示例:
@Value
public class LombokDemo {
@NonNull
private int id;
@NonNull
private String shap;
private int age;
// 相當於
private final int id;
public int getId() {
return this.id;
}
...
}
@Builder
示例:
@Builder
public class BuilderExample {
private String name;
private int age;
@Singular
private Set<String> occupations;
public static void main(String[] args) {
BuilderExample test = BuilderExample.builder().age(11).name("test").build();
}
}
@SneakyThrows
示例:
public class Test {
@SneakyThrows()
public void read() {
InputStream inputStream = new FileInputStream("");
}
@SneakyThrows
public void write() {
throw new UnsupportedEncodingException();
}
// 相當於
public void read() throws FileNotFoundException {
InputStream inputStream = new FileInputStream("");
}
public void write() throws UnsupportedEncodingException {
throw new UnsupportedEncodingException();
}
}
@Synchronized
示例:
public class SynchronizedDemo {
@Synchronized
public static void hello() {
System.out.println("world");
}
// 相當於
private static final Object $LOCK = new Object[0];
public static void hello() {
synchronized ($LOCK) {
System.out.println("world");
}
}
}
@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 AtomicReference<java.lang.Object> cached = new AtomicReference<>();
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;
}
}
4 Lombok 註解原理
說到 Lombok,我們就不得不說「JSR 269: Pluggable Annotation Processing API」。JSR 269 之前我們也有註解這樣的神器,可是我們想要做什麼必須使用反射,而且反射的方法侷限性較大。首先,它必須定義@Retention
爲RetentionPolicy.RUNTIME
,只能在運行時通過反射來獲取註解值,使得運行時代碼效率降低。其次,如果想在編譯階段利用註解來進行一些檢查,對用戶的某些不合理代碼給出錯誤報告,反射的使用方法就無能爲力了。而 JSR 269 之後我們可以在javac
的編譯期利用註解做這些事情,所以其核心的區別就是註解生效的時期,即在運行期還是在編譯期。
從上圖可知,Annotation Processing
是在解析和生成之間的一個步驟,其詳細步驟如下:
上圖是 Lombok 的處理流程,在javac
解析成抽象語法樹之後(AST),Lombok 根據自己的註解處理器,動態的修改 AST,增加新的節點(所謂代碼),最終通過分析和生成字節碼。自從 Java 6 起,javac
就支持 JSR 269 規範,只要程序實現了該 API,就能在javac
運行的時候得到調用。
- 常用的項目管理工具 Maven 所使用的 Java 編譯工具來源於配置的第三方工具,如果我們配置這個第三方工具爲 Oracle
javac
的話,那麼 Maven 也就直接支持 Lombok 了; - IntelliJ IDEA 配置的編譯工具爲 Oracle
javac
的話,也就直接支持 Lombok 了。
IDE 工具問題解決:
- 現在有一個 A 類,其中有一些字段,沒有創建它們的
setter
和getter
方法,使用了 Lombok 的@Data
註解,另外有一個 B 類,它調用了 A 類實例的相應字段的setter
和getter
方法。 - 編譯 A 類和 B 類所在的項目,並不會報錯,因爲最終生成的 A 類字節碼文件中存在相應字段的
setter
和getter
方法 - 但是,IDE 發現 B 類源代碼中所使用的 A 類實例的
setter
和getter
方法在 A 類源代碼中找不到定義,IDE 會認爲這是錯誤 - 要解決以上這個不是真正錯誤的錯誤,可以下載安裝 IntelliJ IDEA 中的
Lombok plugin
插件。
5 自定義支持 JSR 269 的註解
一般javac
的編譯過程,Java 文件首先通過進行解析構建出一個 AST,然後執行註解處理,最後經過分析優化生成二進制的.class
文件。我們能做到的是,在註解處理階段進行一些相應處理。首先我們在META-INF.services
下創建如下文件:
文件中指定我們的註解處理器:com.alipay.kris.other.lombok.MyAnnotaionProcessor
,然後我們可以編寫自己的註解處理器,一個簡單的實例代碼如下:
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes("com.alipay.kris.other.lombok.*")
public class MyAnnotaionProcessor extends AbstractProcessor {
public MyAnnotaionProcessor() {
super();
}
@Override
public boolean process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnv) {
for (Element elem : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
MyAnnotation annotation = elem.getAnnotation(MyAnnotation.class);
String message = "annotation found in " + elem.getSimpleName()
+ " with " + annotation.value();
addToString(elem);
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, message);
}
// no further processing of this annotation type
return true;
}
}