鏈接:https://juejin.im/post/5a6eceb8f265da3e467555fe
來源:掘金
1.簡介
Lombok是一種Java?實(shí)用工具矛双,可用來幫助開發(fā)人員消除Java的冗長代碼,尤其是對于簡單的Java對象(POJO)执解。它通過注釋實(shí)現(xiàn)這一目的。通過在開發(fā)環(huán)境中實(shí)現(xiàn)Lombok润歉,開發(fā)人員可以節(jié)省構(gòu)建諸如hashCode()和equals()這樣的方法以及以往用來分類各種accessor和mutator的大量時(shí)間百拓。
2.IntelliJ安裝Lombok
1.通過IntelliJ的插件中心安裝
2.Install Plugin
3.最后需要注意的是,在使用lombok注解的時(shí)候記得要導(dǎo)入lombok.jar包到工程欲芹,如果使用的是Maven Project,要在pom.xml中添加依賴吟吝。
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.8</version>
</dependency>
3.Lombok用法
3.1 Lombok注解說明
-
val
:用在局部變量前面菱父,相當(dāng)于將變量聲明為final -
@NonNull
:給方法參數(shù)增加這個(gè)注解會自動(dòng)在方法內(nèi)對該參數(shù)進(jìn)行是否為空的校驗(yàn),如果為空,則拋出NPE(NullPointerException) -
@Cleanup
:自動(dòng)管理資源浙宜,用在局部變量之前官辽,在當(dāng)前變量范圍內(nèi)即將執(zhí)行完畢退出之前會自動(dòng)清理資源,自動(dòng)生成try-finally這樣的代碼來關(guān)閉流 -
@Getter/@Setter
:用在屬性上粟瞬,再也不用自己手寫setter和getter方法了野崇,還可以指定訪問范圍 -
@ToString
:用在類上,可以自動(dòng)覆寫toString方法亩钟,當(dāng)然還可以加其他參數(shù),例如@ToString(exclude=”id”)排除id屬性鳖轰,或者@ToString(callSuper=true, includeFieldNames=true)調(diào)用父類的toString方法清酥,包含所有屬性 -
@EqualsAndHashCode
:用在類上,自動(dòng)生成equals方法和hashCode方法 -
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
:用在類上蕴侣,自動(dòng)生成無參構(gòu)造和使用所有參數(shù)的構(gòu)造函數(shù)以及把所有@NonNull屬性作為參數(shù)的構(gòu)造函數(shù)焰轻,如果指定staticName = “of”參數(shù),同時(shí)還會生成一個(gè)返回類對象的靜態(tài)工廠方法昆雀,比使用構(gòu)造函數(shù)方便很多 -
@Data
:注解在類上辱志,相當(dāng)于同時(shí)使用了@ToString
、@EqualsAndHashCode
狞膘、@Getter
揩懒、@Setter
和@RequiredArgsConstrutor
這些注解,對于POJO類
十分有用 -
@Value
:用在類上挽封,是@Data的不可變形式已球,相當(dāng)于為屬性添加final聲明,只提供getter方法辅愿,而不提供setter方法*@Builder
:用在類智亮、構(gòu)造器、方法上点待,為你提供復(fù)雜的builder APIs阔蛉,讓你可以像如下方式一樣調(diào)用Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build();
更多說明參考Builder -
@SneakyThrows
:自動(dòng)拋受檢異常,而無需顯式在方法上使用throws語句*@Synchronized
:用在方法上癞埠,將方法聲明為同步的状原,并自動(dòng)加鎖,而鎖對象是一個(gè)私有的屬性$lock
或$LOCK
燕差,而java中的synchronized關(guān)鍵字鎖對象是this遭笋,鎖在this或者自己的類對象上存在副作用,就是你不能阻止非受控代碼去鎖this或者類對象徒探,這可能會導(dǎo)致競爭條件或者其它線程錯(cuò)誤*@Getter(lazy=true)
:可以替代經(jīng)典的Double Check Lock樣板代碼 -
@Log
:根據(jù)不同的注解生成不同類型的log對象瓦呼,但是實(shí)例名稱都是log,有六種可選實(shí)現(xiàn)類- 1 .
@CommonsLog
Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class); - 2 .
@Log
Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName()); - 3 .
@Log4j
Creates log = org.apache.log4j.Logger.getLogger(LogExample.class); - 4 .
@Log4j2
Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class); - 5 .
@Slf4j
Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class); - 6 .
@XSlf4j
Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
- 1 .
3.2 Lombok代碼示例
3.2.1val示例
public static void main(String[] args) {
val sets = new HashSet<String>();
val lists = new ArrayList<String>();
val maps = new HashMap<String, String>();
//=>相當(dāng)于如下
final Set<String> sets2 = new HashSet<>();
final List<String> lists2 = new ArrayList<>();
final Map<String, String> maps2 = new HashMap<>();
}
3.2.2@NonNull示例
該注解需應(yīng)用在方法或構(gòu)造器的參數(shù)上或?qū)傩陨希脕砼袛鄥?shù)的合法性央串,默認(rèn)拋出 NullPointerException 異常
public void notNullExample(@NonNull String string) {
string.length();
}
//=>相當(dāng)于
public void notNullExample(String string) {
if (string != null) {
string.length();
} else {
throw new NullPointerException("null");
}
}
查看 NonNullExample.class 文件磨澡,會為我們拋出空指針異常,如下圖:
當(dāng)然我們可以通過指定異常類型拋出其他異常质和,lombok.nonNull.exceptionType = [NullPointerException | IllegalArgumentException] , 為實(shí)現(xiàn)此功能我們需要在項(xiàng)目的根目錄新建 lombok.config 文件:
重新編譯 NonNullExample 類稳摄,已經(jīng)為我們拋出非法參數(shù)異常:
3.2.3@Cleanup示例
public static void main(String[] args) {
try {
@Cleanup InputStream inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//=>相當(dāng)于
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();
}
}
}
}
3.2.4@Getter/@Setter示例
該注解可應(yīng)用在類或成員變量之上,和我們預(yù)想的一樣饲宿,@Getter 和 @Setter 就是為成員變量自動(dòng)生成 get 和 set 方法厦酬,默認(rèn)生成訪問權(quán)限為 public 方法,當(dāng)然我們也可以指定訪問權(quán)限 protected 等瘫想,如下圖
成員變量 name 指定生成 set 方法仗阅,并且訪問權(quán)限為 protected;boolean 類型的成員變量 female 只生成 get 方法国夜,并修改方法名稱為 isFemale()减噪。當(dāng)把該注解應(yīng)用在類上,默認(rèn)為所有非靜態(tài)成員變量生成 get 和 set 方法车吹,也可以通過 AccessLevel.NONE 手動(dòng)禁止生成 get 或 set 方法筹裕,如下圖:
@Setter(AccessLevel.PUBLIC)
@Getter(AccessLevel.PROTECTED)
private int id;
private String shap;
3.2.5@ToString示例
該注解需應(yīng)用在類上,為我們生成 Object 的 toString 方法窄驹,而該注解里面的幾個(gè)屬性能更加豐富我們想要的內(nèi)容, exclude 屬性禁止在 toString 方法中使用某字段朝卒,而 of 屬性可以指定需要使用的字段
@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());
}
}
3.2.6@EqualsAndHashCode示例
@EqualsAndHashCode(exclude = {"id", "shape"}, callSuper = false)
public class LombokDemo {
private int id;
private String shap;
}
3.2.7@NoArgsConstructor, @RequiredArgsConstructor and @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");
//使用靜態(tài)工廠方法
LombokDemo.of(2, "circle");
//無參構(gòu)造
new LombokDemo();
//包含所有參數(shù)
new LombokDemo(1, "circle", 2);
}
}
3.2.8@Data示例
介紹了以上的注解,再來介紹 @Data 就非常容易懂了馒吴,@Data 注解應(yīng)用在類上扎运,是 @ToString, @EqualsAndHashCode, @Getter / @Setter 和 @RequiredArgsConstructor 合力的體現(xiàn),
import lombok.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;
//默認(rèn)閾值
private float thresHold = 0;
//新閾值
private float newThresHold = 0;
//總得分
private float totalScore = 0;
}
3.2.9@Value示例
@Value
public class LombokDemo {
@NonNull
private int id;
@NonNull
private String shap;
private int age;
//相當(dāng)于
private final int id;
public int getId() {
return this.id;
}
...
}
3.2.10@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();
}
}
3.2.11@SneakyThrows示例
import lombok.SneakyThrows;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class Test {
@SneakyThrows()
public void read() {
InputStream inputStream = new FileInputStream("");
}
@SneakyThrows
public void write() {
throw new UnsupportedEncodingException();
}
//相當(dāng)于
public void read() throws FileNotFoundException {
InputStream inputStream = new FileInputStream("");
}
public void write() throws UnsupportedEncodingException {
throw new UnsupportedEncodingException();
}
}
3.2.12@Synchronized示例
public class SynchronizedDemo {
@Synchronized
public static void hello() {
System.out.println("world");
}
//相當(dāng)于
private static final Object $LOCK = new Object[0];
public static void hello() {
synchronized ($LOCK) {
System.out.println("world");
}
}
}
3.2.13@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;
}
}
// 相當(dāng)于如下所示:
import java.util.concurrent.atomic.AtomicReference;
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;
}
}