自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

簡(jiǎn)化開發(fā)|Lombok神器帶你消除冗余代碼

開發(fā) 前端
Lombok是一款Java開發(fā)插件,使得Java開發(fā)者可以通過(guò)其定義的一些注解來(lái)消除業(yè)務(wù)過(guò)程中冗余的代碼,尤其是簡(jiǎn)單的Java模型對(duì)象(POJO)。

[[351338]]

 前言

Lombok是一款Java開發(fā)插件,使得Java開發(fā)者可以通過(guò)其定義的一些注解來(lái)消除業(yè)務(wù)過(guò)程中冗余的代碼,尤其是簡(jiǎn)單的Java模型對(duì)象(POJO)。而當(dāng)我們?nèi)绻陂_發(fā)環(huán)境中使用Lombok開發(fā)插件后,可以省出重復(fù)構(gòu)建,諸如hashCode和equals這樣的方法以及各種業(yè)務(wù)對(duì)象模型的accessor和ToString等方法的大量時(shí)間。對(duì)于這些方法,它能夠在編譯源代碼期間自動(dòng)幫我們生產(chǎn)這些方法,并沒(méi)有如反射那樣降低程序的性能。本文將帶大家詳細(xì)介紹關(guān)于Lombok的使用以及原理。

1. Lombok的概念

「概念:」

Lombok是一種Java實(shí)用工具,可以用來(lái)幫助開發(fā)人員消除冗余的代碼,對(duì)于一些簡(jiǎn)單的Java對(duì)象(POJO),它通過(guò)注釋實(shí)現(xiàn)這一目的。

2、Lombok的安裝

「安裝步驟:」

在IDEA的插件Plugins中搜索Lombok

安裝Lombok

「注意:」

在使用Lombok注解的時(shí)候記得要導(dǎo)入Lombok.jar包到工程,Maven Project的話,要在pom.xml中添加依賴

  1. <dependency> 
  2.     <groupId>org.projectlombok</groupId> 
  3.     <artifactId>lombok</artifactId> 
  4.     <version>1.16.8</version> 
  5. </dependency> 

3、Lombok注解說(shuō)明 

「常用注解:」

  1. Lombok注解說(shuō)明 
  2. * val:用在局部變量前面,相當(dāng)于將變量聲明為final 
  3. * @NonNull:給方法參數(shù)增加這個(gè)注解會(huì)自動(dòng)在方法內(nèi)對(duì)該參數(shù)進(jìn)行是否為空的校驗(yàn),如果為空,則拋出NPE(NullPointerException) 
  4. * @Cleanup:自動(dòng)管理資源,用在局部變量之前,在當(dāng)前變量范圍內(nèi)即將執(zhí)行完畢退出之前會(huì)自動(dòng)清理資源,自動(dòng)生成try-finally這樣的代碼來(lái)關(guān)閉流 
  5. * @Getter/@Setter:用在屬性上,再也不用自己手寫setter和getter方法了,還可以指定訪問(wèn)范圍 
  6. * @ToString:用在類上,可以自動(dòng)覆寫toString方法,當(dāng)然還可以加其他參數(shù),例如@ToString(exclude=”id”)排除id屬性,或者@ToString(callSuper=true, includeFieldNames=true)調(diào)用父類的toString方法,包含所有屬性 
  7. * @EqualsAndHashCode:用在類上,自動(dòng)生成equals方法和hashCode方法 
  8. * @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor:用在類上,自動(dòng)生成無(wú)參構(gòu)造和使用所有參數(shù)的構(gòu)造函數(shù)以及把所有@NonNull屬性作為參數(shù)的構(gòu)造函數(shù),如果指定staticName = “of”參數(shù),同時(shí)還會(huì)生成一個(gè)返回類對(duì)象的靜態(tài)工廠方法,比使用構(gòu)造函數(shù)方便很多 
  9. * @Data:注解在類上,相當(dāng)于同時(shí)使用了@ToString、@EqualsAndHashCode、@Getter、@Setter和@RequiredArgsConstrutor這些注解,對(duì)于POJO類十分有用 
  10. * @Value:用在類上,是@Data的不可變形式,相當(dāng)于為屬性添加final聲明,只提供getter方法,而不提供setter方法 
  11. * @Builder:用在類、構(gòu)造器、方法上,為你提供復(fù)雜的builder APIs,讓你可以像如下方式一樣調(diào)用Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build();更多說(shuō)明參考Builder 
  12. * @SneakyThrows:自動(dòng)拋受檢異常,而無(wú)需顯式在方法上使用throws語(yǔ)句 
  13. * @Synchronized:用在方法上,將方法聲明為同步的,并自動(dòng)加鎖,而鎖對(duì)象是一個(gè)私有的屬性$lock或$LOCK,而java中的synchronized關(guān)鍵字鎖對(duì)象是this,鎖在this或者自己的類對(duì)象上存在副作用,就是你不能阻止非受控代碼去鎖this或者類對(duì)象,這可能會(huì)導(dǎo)致競(jìng)爭(zhēng)條件或者其它線程錯(cuò)誤 
  14. * @Getter(lazy=true):可以替代經(jīng)典的Double Check Lock樣板代碼 
  15. * @Log:根據(jù)不同的注解生成不同類型的log對(duì)象,但是實(shí)例名稱都是log,有六種可選實(shí)現(xiàn)類 
  16.     * @CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class); 
  17.     * @Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName()); 
  18.     * @Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class); 
  19.     * @Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class); 
  20.     * @Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class); 
  21.     * @XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class); 

4、Lombok代碼示范

「代碼示例:」

val將變量聲明final類型

  1. public static void main(String[] args) { 
  2.     val sets = new HashSet<String>(); 
  3.     val lists = new ArrayList<String>(); 
  4.     val maps = new HashMap<String, String>(); 
  5.     //=>相當(dāng)于如下 
  6.     final Set<String> sets2 = new HashSet<>(); 
  7.     final List<String> lists2 = new ArrayList<>(); 
  8.     final Map<String, String> maps2 = new HashMap<>(); 

@Nonnull為方法和構(gòu)造函數(shù)的參數(shù)提供非空檢查

  1. public void notNullExample(@NonNull String string) { 
  2.     string.length(); 
  3. //=>相當(dāng)于 
  4. public void notNullExample(String string) { 
  5.     if (string != null) { 
  6.         string.length(); 
  7.     } else { 
  8.         throw new NullPointerException("null"); 
  9.     } 

@Cleanup自動(dòng)釋放資源

  1. public static void main(String[] args) { 
  2.     try { 
  3.         @Cleanup InputStream inputStream = new FileInputStream(args[0]); 
  4.     } catch (FileNotFoundException e) { 
  5.         e.printStackTrace(); 
  6.     } 
  7.     //=>相當(dāng)于 
  8.     InputStream inputStream = null
  9.     try { 
  10.         inputStream = new FileInputStream(args[0]); 
  11.     } catch (FileNotFoundException e) { 
  12.         e.printStackTrace(); 
  13.     } finally { 
  14.         if (inputStream != null) { 
  15.             try { 
  16.                 inputStream.close(); 
  17.             } catch (IOException e) { 
  18.                 e.printStackTrace(); 
  19.             } 
  20.         } 
  21.     } 

@Getter/@Setter對(duì)類的屬性字段自動(dòng)生成Get/Set方法

  1. @Setter(AccessLevel.PUBLIC
  2. @Getter(AccessLevel.PROTECTED) 
  3. private int id; 
  4. private String shap; 

@ToString為類生成一個(gè)toString方法

  1. @ToString(exclude = "id", callSuper = true, includeFieldNames = true
  2. public class LombokDemo { 
  3.     private int id; 
  4.     private String name
  5.     private int age; 
  6.     public static void main(String[] args) { 
  7.         //輸出LombokDemo(super=LombokDemo@48524010, name=null, age=0) 
  8.         System.out.println(new LombokDemo()); 
  9.     } 

@EqualsAndHashCode為類生成equals和hasCode方法

  1. @EqualsAndHashCode(exclude = {"id""shape"}, callSuper = false
  2. public class LombokDemo { 
  3.     private int id; 
  4.     private String shap; 

@NoArgsConstructor,@RequiredArgsConstructor and

@AllArgsConstructor,分別為類自動(dòng)生成無(wú)參構(gòu)造,指定參數(shù)構(gòu)造器和包含所有參數(shù)構(gòu)造器

  1. @NoArgsConstructor 
  2. @RequiredArgsConstructor(staticName = "of"
  3. @AllArgsConstructor 
  4. public class LombokDemo { 
  5.     @NonNull 
  6.     private int id; 
  7.     @NonNull 
  8.     private String shap; 
  9.     private int age; 
  10.     public static void main(String[] args) { 
  11.         new LombokDemo(1, "circle"); 
  12.         //使用靜態(tài)工廠方法 
  13.         LombokDemo.of(2, "circle"); 
  14.         //無(wú)參構(gòu)造 
  15.         new LombokDemo(); 
  16.         //包含所有參數(shù) 
  17.         new LombokDemo(1, "circle", 2); 
  18.     } 

@Data在類上使用,相當(dāng)于同時(shí)使用@ToString、

@EqualsAndHashCode、@Getter、@Setter和

@RequiredArgsConstructor這些注解

  1. import lombok.Data; 
  2. @Data 
  3. public class Menu { 
  4.     private String shopId; 
  5.     private String skuMenuId; 
  6.     private String skuName; 
  7.     private String normalizeSkuName; 
  8.     private String dishMenuId; 
  9.     private String dishName; 
  10.     private String dishNum; 
  11.     //默認(rèn)閾值 
  12.     private float thresHold = 0; 
  13.     //新閾值 
  14.     private float newThresHold = 0; 
  15.     //總得分 
  16.     private float totalScore = 0; 

@Value為屬性添加final聲明

  1. @Value 
  2. public class LombokDemo { 
  3.     @NonNull 
  4.     private int id; 
  5.     @NonNull 
  6.     private String shap; 
  7.     private int age; 
  8.     //相當(dāng)于 
  9.     private final int id; 
  10.     public int getId() { 
  11.         return this.id; 
  12.     } 
  13.     ... 

@Builder提供構(gòu)建值對(duì)象方式

  1. @Builder 
  2. public class BuilderExample { 
  3.     private String name
  4.     private int age; 
  5.     @Singular 
  6.     private Set<String> occupations; 
  7.     public static void main(String[] args) { 
  8.         BuilderExample test = BuilderExample.builder().age(11).name("test").build(); 
  9.     } 

@SneakyThrows自動(dòng)拋受檢異常

  1. import lombok.SneakyThrows; 
  2. import java.io.FileInputStream; 
  3. import java.io.FileNotFoundException; 
  4. import java.io.InputStream; 
  5. import java.io.UnsupportedEncodingException; 
  6. public class Test { 
  7.     @SneakyThrows() 
  8.     public void read() { 
  9.         InputStream inputStream = new FileInputStream(""); 
  10.     } 
  11.     @SneakyThrows 
  12.     public void write() { 
  13.         throw new UnsupportedEncodingException(); 
  14.     } 
  15.     //相當(dāng)于 
  16.     public void read() throws FileNotFoundException { 
  17.         InputStream inputStream = new FileInputStream(""); 
  18.     } 
  19.     public void write() throws UnsupportedEncodingException { 
  20.         throw new UnsupportedEncodingException(); 
  21.     } 

@Synchronized將方法聲明同步并自動(dòng)加鎖

  1. public class SynchronizedDemo { 
  2.     @Synchronized 
  3.     public static void hello() { 
  4.         System.out.println("world"); 
  5.     } 
  6.     //相當(dāng)于 
  7.     private static final Object $LOCK = new Object[0]; 
  8.     public static void hello() { 
  9.         synchronized ($LOCK) { 
  10.             System.out.println("world"); 
  11.         } 
  12.     } 

@Getter(lazy=true)可以替代經(jīng)典的Double check Lock樣板代碼

  1. public class GetterLazyExample { 
  2.     @Getter(lazy = true
  3.     private final double[] cached = expensive(); 
  4.     private double[] expensive() { 
  5.         double[] result = new double[1000000]; 
  6.         for (int i = 0; i < result.length; i++) { 
  7.             result[i] = Math.asin(i); 
  8.         } 
  9.         return result; 
  10.     } 
  11.  
  12. // 相當(dāng)于如下所示:  
  13.  
  14. import java.util.concurrent.atomic.AtomicReference; 
  15. public class GetterLazyExample { 
  16.     private final AtomicReference<java.lang.Object> cached = new AtomicReference<>(); 
  17.     public double[] getCached() { 
  18.         java.lang.Object value = this.cached.get(); 
  19.         if (value == null) { 
  20.             synchronized (this.cached) { 
  21.                 value = this.cached.get(); 
  22.                 if (value == null) { 
  23.                     final double[] actualValue = expensive(); 
  24.                     value = actualValue == null ? this.cached : actualValue; 
  25.                     this.cached.set(value); 
  26.                 } 
  27.             } 
  28.         } 
  29.         return (double[]) (value == this.cached ? null : value); 
  30.     } 
  31.     private double[] expensive() { 
  32.         double[] result = new double[1000000]; 
  33.         for (int i = 0; i < result.length; i++) { 
  34.             result[i] = Math.asin(i); 
  35.         } 
  36.         return result; 
  37.     } 

@Log根據(jù)不同的注解生成不同類型的log對(duì)象

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

結(jié)語(yǔ)

本篇關(guān)于Lombok的介紹就先到這里結(jié)束了,后續(xù)會(huì)出更多關(guān)于Lombok系列更多文章,謝謝大家支持!

 

責(zé)任編輯:姜華 來(lái)源: 淺羽的IT小屋
相關(guān)推薦

2012-07-27 10:30:12

重構(gòu)

2013-09-05 09:50:11

C++代碼優(yōu)化

2023-08-11 18:16:08

DevOps開發(fā)

2021-09-03 13:37:25

Lombo代碼Java

2010-05-27 12:30:52

MySQL工具

2019-11-27 10:05:00

LombokJava編程

2010-06-02 10:00:25

MySQL工具

2010-04-13 08:49:08

JavaLombokJavabean

2009-06-11 17:54:00

Visual StudDataSet

2010-01-26 09:10:38

Java EE 6注解Profile

2023-04-02 14:09:51

2017-11-15 06:36:25

JOINSQL運(yùn)算

2010-05-24 09:47:32

AjaxAjax框架

2023-08-09 08:21:26

2010-07-06 10:34:33

RationalJazz需求管理

2024-07-29 00:02:00

DemoVue開發(fā)

2024-02-28 11:33:01

云服務(wù)開發(fā)

2024-04-16 08:48:14

WPF開發(fā)MVVM庫(kù)Prism

2016-03-29 18:22:37

比特網(wǎng)

2023-12-04 07:06:11

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)