返回
顶部

该注解会生成带有参数的构造函数

这里的参数指的是所有final修饰的未初始化的字段以及使用了@NonNull注解修饰的字段

生成的构造函数,默认权限修饰符为public

下面为带注解的代码与不带注解的代码对比

@RequiredArgsConstructor
public class RequiredArgsDemo1 {

  private Long id;

  @NonNull
  private String username;

  @NonNull
  private String email;

  private final boolean status;
}
public class RequiredArgsDemo1 {
  private Long id;
  @NonNull
  private String username;
  @NonNull
  private String email;
  private final boolean status;

  public RequiredArgsDemo1(
      @NonNull final String username, 
      @NonNull final String email, 
      final boolean status
      ) {

    if (username == null) {
      throw new NullPointerException("username is marked non-null but is null");
    }
    if (email == null) {
      throw new NullPointerException("email is marked non-null but is null");
    }
    this.username = username;
    this.email = email;
    this.status = status;
  }
}

可以看到,使用了注解的代码相对于原始代码要简洁很多,无需我们再手动编写含参构造函数