Lombok

2、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 and @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、代碼示例

  • val
  • val示例
       
       
       
       
       
    2
    3
    4
    5
    6
    7
    8
    9
    10
         
     
     
     
       
       
       
    publicstaticvoidmain(String[] args) {    val sets =newHashSet<String>();    val lists =newArrayList<String>();    val maps =newHashMap<String, String>();    //=>至關於以下    finalSet<String> sets2 =newHashSet<>();    finalList<String> lists2 =newArrayList<>();    finalMap<String, String> maps2 =newHashMap<>();}
  • @NonNull示例
2
3
4
public   void   notNullExample( @NonNull   String string) {
   string.length();
}
2
3
4
5
6
7
8
9
//=>至關於
  public   void   notNullExample(String string) {
    if   (string != null ) {
       string.length();
    } else   {
       throw   new   NullPointerException( "null" );
    }
}
  • @Cleanup示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    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示例
       
       
       
       
       
    2
    3
    4
    5
       
     
    @Setter(AccessLevel.PUBLIC)@Getter(AccessLevel.PROTECTED)privateintid;privateString shap;
  • @ToString示例
     
       
       
       
       
       
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
       
       
     
       
     
         
     
    @ToString(exclude ="id", callSuper =true, includeFieldNames =true)publicclassLombokDemo {    privateintid;    privateString name;    privateintage;    publicstaticvoidmain(String[] args) {        //輸出LombokDemo(super=LombokDemo@48524010, name=null, age=0)        System.out.println(newLombokDemo());    }}
  • @EqualsAndHashCode示例
     
       
       
       
       
       
    2
    3
    4
    5
    6
       
       
     

    @EqualsAndHashCode(exclude = {"id","shape"}, callSuper =false)publicclassLombokDemo {    privateintid;    privateString shap;}
  • @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    @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示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    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;
         //默認閾值
         private   float   thresHold = 0 ;
         //新閾值
         private   float   newThresHold = 0 ;
         //總得分
         private   float   totalScore = 0 ;
    }

    在IntelliJ中按下Ctrl+F12就能夠看到Lombok已經爲咱們自動生成了一系列的方法。
    html

  • @Value示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    @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示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @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示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    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();
         }
         //至關於
         public   void   read() throws   FileNotFoundException {
             InputStream inputStream = new   FileInputStream( "" );
         }
         public   void   write() throws   UnsupportedEncodingException {
             throw   new   UnsupportedEncodingException();
         }
    }
  • @Synchronized示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    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)
2
3
4
5
6
7
8
9
10
11
12
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;
   }
}
2
  
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
    }
}

2、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 and @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、代碼示例

  • val
  • val示例
           
           
           
           
           
    2
    3
    4
    5
    6
    7
    8
    9
    10
         
     
     
     
       
       
       
    publicstaticvoidmain(String[] args) {    val sets =newHashSet<String>();    val lists =newArrayList<String>();    val maps =newHashMap<String, String>();    //=>至關於以下    finalSet<String> sets2 =newHashSet<>();    finalList<String> lists2 =newArrayList<>();    finalMap<String, String> maps2 =newHashMap<>();}
  • @NonNull示例
2
3
4
public   void   notNullExample( @NonNull   String string) {
   string.length();
}
2
3
4
5
6
7
8
9
//=>至關於
  public   void   notNullExample(String string) {
    if   (string != null ) {
       string.length();
    } else   {
       throw   new   NullPointerException( "null" );
    }
}
  • @Cleanup示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    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示例
           
           
           
           
           
    2
    3
    4
    5
       
     
    @Setter(AccessLevel.PUBLIC)@Getter(AccessLevel.PROTECTED)privateintid;privateString shap;
  • @ToString示例
     
           
           
           
           
           
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
       
       
     
       
     
         
     
    @ToString(exclude ="id", callSuper =true, includeFieldNames =true)publicclassLombokDemo {    privateintid;    privateString name;    privateintage;    publicstaticvoidmain(String[] args) {        //輸出LombokDemo(super=LombokDemo@48524010, name=null, age=0)        System.out.println(newLombokDemo());    }}
  • @EqualsAndHashCode示例
     
           
           
           
           
           
    2
    3
    4
    5
    6
       
       
     

    @EqualsAndHashCode(exclude = {"id","shape"}, callSuper =false)publicclassLombokDemo {    privateintid;    privateString shap;}
  • @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    @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示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    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;
         //默認閾值
         private   float   thresHold = 0 ;
         //新閾值
         private   float   newThresHold = 0 ;
         //總得分
         private   float   totalScore = 0 ;
    }

    在IntelliJ中按下Ctrl+F12就能夠看到Lombok已經爲咱們自動生成了一系列的方法。
    java

  • @Value示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    @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示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @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示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    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();
         }
         //至關於
         public   void   read() throws   FileNotFoundException {
             InputStream inputStream = new   FileInputStream( "" );
         }
         public   void   write() throws   UnsupportedEncodingException {
             throw   new   UnsupportedEncodingException();
         }
    }
  • @Synchronized示例
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    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)
2
3
4
5
6
7
8
9
10
11
12
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;
   }
}
2
  
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
    }
}



相關文章
相關標籤/搜索