对于Lombok中@NoArgsConstructor、@RequiredArgsConstructor、@AllArgsConstructor注解的详解

由于乙方项目使用到了lombok插件,故对lombok插件注解进行了学习并加以总结,如有不对,欢迎指正。

一、引用

https://projectlombok.org/features/constructor

二、概要

注解 构造函数参数 nonnull校验 备注
@NoArgsConstructor 无参 可使用参数
@RequiredArgsConstructor 未初始化的final字段、标注为nonnull的字段 可使用参数@RequiredArgsConstructor(staticName = “of”),将构造方法私有化,并提供静态函数of创建构造函数。
@AllArgsConstrutor 所有字段有可使用参数 @AllArgsConstrutor(access = AccessLevel.PROTECTED)来控制构造函数的访问级别。

三、详细

@NoArgsConstructor

@NoArgsConstructor
用于生成无参构造函数。如果因为final字段未初始化导致构造失败,则会导致编译失败。可以使用@NoArgsConstructor(force
= true)参数,从而强制将未初始化的fianl字段赋值为 0 / false / null。 对于具有约束的字段(例如 @NonNull 字段),不会进行检查。因此请注意,正确初始化这些字段之前,这些约束无效。

@RequiredArgsConstructor

@RequiredArgsConstructor
为有需要特殊处理的字段生成带有一个参数的构造函数,所有未能初始化的fianl字段,以及被标记为@NonNull且在声明时没有初始化的字段,都是该构造函数的参数。
参数的顺序与类中字段出现的顺序是保持一致的,对于@NonNull的字段也会进行空值检查,如果不符合校验规则,抛出空指针异常。

@AllArgsConstructor

@AllArgsConstructor:为类中的每个字段生成一个具有1个参数的构造函数。 标记为@Non Null的字段会进行空值检查。

四、案例

使用lombok注解

import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.NonNull;

@RequiredArgsConstructor(staticName = "of")
//增加RequiredArgsConstructor注解,可以对description字段生成私有构造函数,同时提供一个静态函数of进行创建。
@AllArgsConstructor(access = AccessLevel.PROTECTED)
//增加了AllArgsConstructor注解,可以生成一个全参构造函数,访问权限为protected。
public class ConstructorExample<T> {
    
    
  private int x, y;
  @NonNull private T description;
  
  @NoArgsConstructor
  //静态内部类,创建一个无参构造,对于field字段不做校验。
  public static class NoArgsExample {
    
    
    @NonNull private String field;
  }
}

不使用lombok注解

public class ConstructorExample<T> {
    
    
  private int x, y;
  @NonNull private T description;
  
  //创建了私有构造方法,参数为description,并对其进行非null校验。然后创建了静态of方法创建构造方法。
  private ConstructorExample(T description) {
    
    
    if (description == null) throw new NullPointerException("description");
    this.description = description;
  }
  
  public static <T> ConstructorExample<T> of(T description) {
    
    
    return new ConstructorExample<T>(description);
  }
  
  @java.beans.ConstructorProperties({
    
    "x", "y", "description"})
  //按参数顺序创建构造了函数,并对description字段做了校验。
  protected ConstructorExample(int x, int y, T description) {
    
    
    if (description == null) throw new NullPointerException("description");
    this.x = x;
    this.y = y;
    this.description = description;
  }
  
  public static class NoArgsExample {
    
    
    @NonNull private String field;
    //静态内部类的无参构造
    public NoArgsExample() {
    
    
    }
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_44159662/article/details/109990456