Lombok @NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor注解

Lombok @NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor注解

@NoArgsConstructor

@NoArgsConstructor用来指定无参数构造器,如果设置@NoArgsConstructor(force = true),参数意味着所有final字段被初始化为 0 / false / null。

@RequiredArgsConstructor

@RequiredArgsConstructor每个需要特殊处理的字段生成一个带有相应参数的构造函数。生成的构造方法是private,如何想要对外提供使用可以使用staticName选项生成一个static方法,即@RequiredArgsConstructor(staticName="of")

@AllArgsConstructor

@AllArgsConstructor为类中的每个字段生成一个带有1个参数的构造函数,对标记为的字段@NonNull对进行空参校验。

对比12

使用了lombok


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

@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class ConstructorExample<T> {
  private int x, y;
  @NonNull private T description;
  
  @NoArgsConstructor
  public static class NoArgsExample {
    @NonNull private String field;
  }
}

未使用lombok


public class ConstructorExample<T> {
  private int x, y;
  @NonNull private T description;
  
  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"})
  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() {
    }
  }
}

  1. https://projectlombok.org/features/constructor ↩︎

  2. https://projectlombok.org/features/constructor ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值