lombok使用


TOC

lombok使用

類注解:

data

@Data :注解在類上;提供類所有屬性的 getting 和 setting 方法,此外還提供了equals、canEqual、hashCode、toString 方法,

public class Demo3 {
    private Long id;
    private String name;

    public Demo3() {
    }

    public Long getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public boolean equals(final Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof Demo3)) {
            return false;
        } else {
            Demo3 other = (Demo3)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                Object this$id = this.getId();
                Object other$id = other.getId();
                if (this$id == null) {
                    if (other$id != null) {
                        return false;
                    }
                } else if (!this$id.equals(other$id)) {
                    return false;
                }

                Object this$name = this.getName();
                Object other$name = other.getName();
                if (this$name == null) {
                    if (other$name != null) {
                        return false;
                    }
                } else if (!this$name.equals(other$name)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(final Object other) {
        return other instanceof Demo3;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $id = this.getId();
        int result = result * 59 + ($id == null ? 43 : $id.hashCode());
        Object $name = this.getName();
        result = result * 59 + ($name == null ? 43 : $name.hashCode());
        return result;
    }

    public String toString() {
        return "Demo3(id=" + this.getId() + ", name=" + this.getName() + ")";
    }
}

@Data(staticConstructor="methodName")來生成一個靜態方法,返回一個調用相應的構造方法產生的對象。

//默認
public Demo3() {}

//@Data(staticConstructor="getDemo3")
    private Demo3() {
    }

    public static Demo3 getDemo3() {
        return new Demo3();
    }

Setter和Getter

  • @Setter:注解在屬性上;為屬性提供 setting 方法
  • @Getter:注解在屬性上;為屬性提供 getting 方法

Setter和Getter也可以設置到字段上,並設置方法級別

public class Programmer{
      @Getter
      @Setter
      private String name;

      @Setter(AccessLevel.PROTECTED)
      private int age;

      @Getter(AccessLevel.PUBLIC)
      private String language;
  }
  ----------------
  public class Programmer{
      private String name;
      private int age;
      private String language;
      public void setName(String name){this.name = name;}
      public String getName(){return name;}
      protected void setAge(int age){this.age = age;}
      public String getLanguage(){return language;}
  }

Value

@Value :Getter、toString()、equals()、hashCode()、一個全參的構造方法

Builder

@Builder:Builder內部類和全字段的構造器,沒有Getter、Setter、toString()。

@ToString
@Builder
public class Demo3 {
    private Long id;
    private String name;

    public static void main(String[] args) {
        Demo3 nihao = Demo3.builder().id(12L).name("nihao").build();
        System.out.println(nihao);
    }
}
//Demo3(id=12, name=nihao)

ToString

@ToString:toString()方法:@ToString(exclude={"param1","param2"})來排除param1和param2兩個成員變量,或者用@ToString(of={"param1","param2"})來指定使用param1和param2兩個成員變量

EqualsAndHashCode

@EqualsAndHashCode:equals、canEqual(用於判斷某個對象是否是當前類的實例,生成方法時只會使用類中的非靜態非transient成員變量)和hashcode方法,@EqualsAndHashCode(exclude={“param1”,“param2”})來排除param1和param2兩個成員變量,或者用@EqualsAndHashCode(of={“param1”,“param2”})來指定使用param1和param2兩個成員變量

繼承類一般都會加上:@EqualsAndHashCode(callSuper=false)

Cleanup

@Cleanup:該注解的對象,如Stream對象,如果有close()方法,那么在該對象作用域離開時會自動關閉。

    @SneakyThrows  //等同於try/catch 捕獲異常
    public static void main(String[] args)  {
        @Cleanup// : 可以關閉流
        BufferedReader br = new BufferedReader(new FileReader("aa.txt"));
        @Cleanup// : 可以關閉流
        BufferedWriter bw = new BufferedWriter(new FileWriter("bb.txt"));

        int ch;
        while ((ch = br.read()) != -1) {
            bw.write(ch);
        }
//        bw.close();
//        br.close();
    }
-----編譯之后
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("aa.txt"));

            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter("bb.txt"));

                int ch;
                try {
                    while((ch = br.read()) != -1) {
                        bw.write(ch);
                    }
                } finally {
                    if (Collections.singletonList(bw).get(0) != null) {
                        bw.close();
                    }

                }
            } finally {
                if (Collections.singletonList(br).get(0) != null) {
                    br.close();
                }

            }

        } catch (Throwable var14) {
            throw var14;
        }
    }

日志

  • @Log:一組日志相關注解,標注的類會隱式的定一個了一個名為log的日志對象。
  • @Log4j :注解在類上;為類提供一個 屬性名為log 的 log4j 日志對象
  • @Log4j2@Slf4j@XSlf4j,@CommonsLog,@JBossLog
 @Log
public  class User {
    public  static  void  main(String[] args) {
        System.out.println(log.getClass()); 
        log.info("app log."); 
    }
}

構造器

構造器(上面的三個注解)可以使用access屬性定制訪問級別,如:@NoArgsConstructor(access = AccessLevel.PRIVATE)

  • @NoArgsConstructor:注解在類上;為類提供一個無參的構造方法,有時候我們會使用到單例模式,這個時候我們需要將構造器私有化,那么就可以使用這樣一個屬性access設置構造器的權限.

    當類中有final字段沒有被初始化時,編譯器會報錯,但是也可用@NoArgsConstructor(force = true),那么Lombok就會為沒有初始化的final字段設置默認值 0 / false / null, 這樣編譯器就不會報錯,如下所示:

    @NoArgsConstructor(force = true)
    public class User {
      private final String gender;
      private String username;
      private String password;
    }
    // 編譯后:
    public class User {
      private final String gender = null;
      private String username;
      private String password;
    
      public User() { }
    }

對於具有約束的字段(例如使用了@NonNull注解的字段),不會生成字段檢查

  • staticName:定義一個姓的構造方法,默認的構造方法會被私有化
    @NoArgsConstructor(staticName = "UserHa")//@Data(staticConstructor="methodName")
    public class User {
        private String username;
        private String password;
    }
    // 編譯后:
    public class User {
        private String username;
        private String password;
    
        private User() { } //私有了
    
        public static User UserHa() { //根據注解,生成了一個新的注解
            return new User();
        }
    }
    • @AllArgsConstructor:注解在類上;為類提供一個全參的構造方法,(不包括已初始化的final字段)
    • @RequiredArgsConstructor: 增加必選參數構造器,只能是類中所有帶有 @NonNull注解的和以final修飾的未經初始化的字段才會被納入 RequiredArgsConstructor 構造器中。
    @RequiredArgsConstructor
    public class User {
      private final String gender;
      @NonNull
      private String username;
      private String password;
    }
    
    // 編譯后:
    public class User {
      private final String gender;
      @NonNull
      private String username;
      private String password;
    
      public User(String gender, @NonNull String username) {
          //@NonNull的校驗不能為null
          if (username == null) {
              throw new NullPointerException("username is marked @NonNull but is null");
          } else {
              this.gender = gender;
              this.username = username;
          }
      }
    }
    • Constructor 全局配置
    # 如果設置為true,則lombok將向生成的構造函數添加 @java.beans.ConstructorProperties。
    
    lombok.anyConstructor.addConstructorProperties = [true | false] (default: false)
    
    # 是否禁用這幾種構造器注解
    
    lombok.[allArgsConstructor|requiredArgsConstructor|noArgsConstructor].flagUsage = [warning | error] (default: not set)
    lombok.anyConstructor.flagUsage = [warning | error] (default: not set)
    
    # 是否支持復制現有的注解,在本類中使用。e.g. @Nullable/@NonNull annotations
    
    lombok.copyableAnnotations = [A list of fully qualified types] (default: empty list)
  • 測試 addConstructorProperties

    全局配置文件內容

    config.stopBubbling = true
    
    # 首先清除原有配置
    
    clear lombok.anyConstructor.addConstructorProperties
    
    # 設置新的配置
    
    lombok.anyConstructor.addConstructorProperties = true

    實體類

    //值得注意一點的是:@ConstructorProperties只能用在JDK 6中
    @AllArgsConstructor
    public class User {
        private String username;
        private String password;
    }
    // 編譯后:
    public class User {
        private String username;
        private String password;
    
        @ConstructorProperties({"username", "password"})        // 被添加
        public User(String username, String password) {
            this.username = username;
            this.password = password;
        }
    }

Accessors

@Accessors:用於配置getter和setter方法的生成結果

  • fluent:

    fluent的中文含義是流暢的,設置為true,則getter和setter方法的方法名都是基礎屬性名,且setter方法返回當前對象。

    @Data
    @Accessors(fluent = true)
    public class User {
      private Long id;
      private String name;
    
      // 生成的getter和setter方法如下,方法體略
      public Long id() {}
      public User id(Long id) {}
      public String name() {}
      public User name(String name) {}
    }
  • chain:設置為true,則setter方法返回當前對象。
    @Data
    @Accessors(chain = true)
    public class User {
      private Long id;
      private String name;
    
      // 生成的setter方法如下,方法體略
      public User setId(Long id) {}
      public User setName(String name) {}
    }
  • prefix:用於生成getter和setter方法的字段名會忽視指定前綴(遵守駝峰命名)。
    @Data
    @Accessors(prefix = "p")
    class User {
      private Long pId;
      private String pName;
    
      // 生成的getter和setter方法如下,方法體略
      public Long getId() {}
      public void setId(Long id) {}
      public String getName() {}
      public void setName(String name) {}
    }

Synchronized

這個注解用在類方法或者實例方法上,效果和synchronized關鍵字相同,區別在於鎖對象不同,對於類方法和實例方法,synchronized關鍵字的鎖對象分別是類的class對象和this對象,而@Synchronized得鎖對象分別是私有靜態final對象LOCK和私有final對象LOCK和私有final對象lock,當然,也可以自己指定鎖對象

public class Synchronized {
    private final Object readLock = new Object();

    @Synchronized
    public static void hello() {
        System.out.println("world");
    }

    @Synchronized
    public int answerToLife() {
        return 42;
    }

    @Synchronized("readLock")
    public void foo() {
        System.out.println("bar");
    }
}

編譯后:

public class Synchronized {
   private static final Object $LOCK = new Object[0];
   private final Object $lock = new Object[0];
   private final Object readLock = new Object();

   public static void hello() {
     synchronized($LOCK) {
       System.out.println("world");
     }
   }

   public int answerToLife() {
     synchronized($lock) {
       return 42;
     }
   }

   public void foo() {
     synchronized(readLock) {
       System.out.println("bar");
     }
   }
}

屬性注解

懶加載

是對象初始化時,該字段並不會真正的初始化;而是第一次訪問該字段時才進行初始化字段的操作。

  • lazy
@Getter(lazy=true) 懶加載
package com.pollyduan;

import lombok.Data;
import lombok.Getter;

@Data
public class GetterLazyExample {
    @Getter(lazy = true)
    private final int[] cached = expensive();
    private Integer id;

    private int[] expensive() {
        int[] result = new int[100];
        for (int i = 0; i < result.length; i++) {
            result[i] = i;
            System.out.println(i);
        }
        System.out.println("cached 初始化完成。");
        return result;
    }
    public static void main(String[] args) {
        GetterLazyExample obj=new GetterLazyExample();
        obj.setId(1001);
        System.out.println("打印id:"+obj.getId());
        System.out.println("cached 還沒有初始化喲。");
        // obj.getCached();
    }
}
打印id:1001
cached 還沒有初始化。
打開obj.getCached();的注釋,獲取這個字段的值,你就會發現它真的初始化了。
打印id:1001 cached 還沒有初始化喲。 0  1  ...  97  98  99 cached 初始化完成。
  • @SneakyThrows 隱藏異常,自動捕獲檢查異常。可以將方法中的代碼用try-catch語句包裹起來,捕獲異常並在catch中用Lombok.sneakyThrow(e)把異常拋出,可以使用@SneakyThrows(異常類.class)的形式指定拋出哪種異常

提示:不過這並不是友好的編碼方式,因為你編寫的api的使用者,不能顯式的獲知需要處理檢查異常。

import lombok.SneakyThrows;

public class SneakyThrowsExample {
    @SneakyThrows({UnsupportedEncodingException.class})
    public void test(byte[] bytes) {
        String str = new String(bytes, "UTF8");
    }
    @SneakyThrows({UnsupportedEncodingException.class,FileNotFoundException.class})
    public void test2(byte[] bytes) {
        FileInputStream file=new FileInputStream("no_texists.txt");
        String str=new String(bytes, "UTF8");
    }
    @SneakyThrows
    public void test3(byte[] bytes) {
        FileInputStream file=new FileInputStream("no_texists.txt");
        String str=new String(bytes, "UTF8");
    }

}

編譯之后:

package com.pollyduan;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

import lombok.SneakyThrows;

public class SneakyThrowsExample {
    public void test(byte[] bytes) {
        try {
            String str = new String(bytes, "UTF8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public void test2(byte[] bytes) {
        try {
            FileInputStream file=new FileInputStream("no_texists.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            String str=new String(bytes, "UTF8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public void test3(byte[] bytes) {
        try {
            FileInputStream file=new FileInputStream("no_texists.txt");
            String str=new String(bytes, "UTF8");
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}

輔助注解

NonNull

@NonNull:

標記在字段上,表示非空字段。

標注在方法參數上,會在第一次使用該參數是判斷是否為空,如果參數為空,則拋出一個空指針異常 。

//成員方法參數加上@NonNull注解
public String getName(@NonNull Person p){
    return p.getName();
}
---------------
public String getName(@NonNull Person p){
    if(p==null){
        throw new NullPointerException("person");
    }
    return p.getName();
}

Cleanup

@Cleanup:自動關閉資源,如果該資源有其它關閉方法,可使用@Cleanup(“methodName”)來指定要調用的方法.

public static void main(String[] args) throws IOException {
     @Cleanup InputStream in = new FileInputStream(args[0]);
     @Cleanup OutputStream out = new FileOutputStream(args[1]);
     byte[] b = new byte[1024];
     while (true) {
       int r = in.read(b);
       if (r == -1) break;
       out.write(b, 0, r);
     }
}
--------------------
public static void main(String[] args) throws IOException {
     InputStream in = new FileInputStream(args[0]);
     try {
       OutputStream out = new FileOutputStream(args[1]);
       try {
         byte[] b = new byte[10000];
         while (true) {
           int r = in.read(b);
           if (r == -1) break;
           out.write(b, 0, r);
         }
       } finally {
         if (out != null) {
           out.close();
         }
       }
     } finally {
       if (in != null) {
         in.close();
       }
    }
}





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM