在Lombok中,生成構造方法的annotation一共有三個,@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsContructor。使用這三個annotation來完成項目中對於不同構造方法的需求。
@NoArgsConstructor : 生成一個無參數的構造方法,這個annotation在與其他的annotation配合起來使用的時候更加能凸顯出他的重要性,例如在使用hibernate這種框架的時候,如果有一個有參數的構造方法的時候,NoArgsConstructor會展示出他的作用。
@RequiredArgsConstructor: 會生成一個包含常量,和標識了NotNull的變量 的構造方法。生成的構造方法是private,如何想要對外提供使用可以使用staticName選項生成一個static方法。
@AllArgsContructor: 會生成一個包含所有變量,同時如果變量使用了NotNull annotation , 會進行是否爲空的校驗, 我們來看一下官方給出的一個例子:
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.NonNull;
@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;
}
}
上面的例子用Java代碼翻譯一下就是:
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() {
}
}
}
如果是@AllArgsConstructor 在生成的構造函數上會生成一@ConstructorProperties 的Java annotation, 當然也可以通過將suppressConstructorProperties 設置爲true來禁用@ConstructorProperties 。 如果你知道@ConstructorProperties 是幹什麼用的,那麼一定就知道@NoArgsConstructor爲什麼沒有這個配置參數了。
值得注意一點的是:@ConstructorProperties 只能用在JDK 6 中