Lombok 之 Constructor

Lombok 之 Constructor

《摘自erweimaerweima》的内容

在Lombok中,生成构造方法的annotation一共有三个,@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsContructor。使用这三个annotation来完成项目中对于不同构造方法的需求。

 
@NoArgsConstructor : 生成一个无参数的构造方法,这个annotation在与其他的annotation配合起来使用的时候更加能凸显出他的重要性,例如在使用hibernate这种框架的时候,如果有一个有参数的构造方法的时候,NoArgsConstructor会展示出他的作用。
 
@RequiredArgsConstructor: 会生成一个包含常量,和标识了NotNull的变量 的构造方法。生成的构造方法是private,如何想要对外提供使用可以使用staticName选项生成一个static方法。
 

@AllArgsContructor:  会生成一个包含所有变量,同时如果变量使用了NotNull annotation , 会进行是否为空的校验, 我们来看一下官方给出的一个例子:

[java] view plain copy
 
  1. import lombok.AccessLevel;  
  2. import lombok.RequiredArgsConstructor;  
  3. import lombok.AllArgsConstructor;  
  4. import lombok.NonNull;  
  5.   
  6. @RequiredArgsConstructor(staticName = "of")  
  7. @AllArgsConstructor(access = AccessLevel.PROTECTED)  
  8. public class ConstructorExample<T> {  
  9.   private int x, y;  
  10.   @NonNull private T description;  
  11.     
  12.   @NoArgsConstructor  
  13.   public static class NoArgsExample {  
  14.     @NonNull private String field;  
  15.   }  
  16. }  

上面的例子用Java代码翻译一下就是:

[java] view plain copy
 
  1. public class ConstructorExample<T> {  
  2.   private int x, y;  
  3.   @NonNull private T description;  
  4.     
  5.   private ConstructorExample(T description) {  
  6.     if (description == null) throw new NullPointerException("description");  
  7.     this.description = description;  
  8.   }  
  9.     
  10.   public static <T> ConstructorExample<T> of(T description) {  
  11.     return new ConstructorExample<T>(description);  
  12.   }  
  13.     
  14.   @java.beans.ConstructorProperties({"x", "y", "description"})  
  15.   protected ConstructorExample(int x, int y, T description) {  
  16.     if (description == null) throw new NullPointerException("description");  
  17.     this.x = x;  
  18.     this.y = y;  
  19.     this.description = description;  
  20.   }  
  21.     
  22.   public static class NoArgsExample {  
  23.     @NonNull private String field;  
  24.     public NoArgsExample() {  
  25.     }  
  26.   }  
  27. }  

 如果是@AllArgsConstructor 在生成的构造函数上会生成一@ConstructorProperties 的Java annotation, 当然也可以通过将suppressConstructorProperties 设置为true来禁用@ConstructorProperties 。 如果你知道@ConstructorProperties 是干什么用的,那么一定就知道@NoArgsConstructor为什么没有这个配置参数了。
 
值得注意一点的是:@ConstructorProperties 只能用在JDK 6 中
原文地址:https://www.cnblogs.com/tianlifitting/p/8038100.html