Akashic Records

Lombok features - @NonNull 본문

Library

Lombok features - @NonNull

Andrew's Akashic Records 2020. 12. 9. 16:37
728x90

@NonNull

or: How I learned to stop worrying and love the NullPointerException.

@NonNull was introduced in lombok v0.11.10.

Overview

You can use @NonNull on the parameter of a method or constructor to have lombok generate a null-check statement for you.

Lombok has always treated various annotations generally named @NonNull on a field as a signal to generate a null-check if lombok generates an entire method or constructor for you, via for example @Data. Now, however, using lombok's own @lombok.NonNull on a parameter results in the insertion of just the null-check statement inside your own method or constructor.

The null-check looks like if (param == null) throw new NullPointerException("param is marked @NonNull but is null"); and will be inserted at the very top of your method. For constructors, the null-check will be inserted immediately following any explicit this() or super() calls.

If a null-check is already present at the top, no additional null-check will be generated.

With Lombok

import lombok.NonNull;

public class NonNullExample extends Something {
  private String name;
  
  public NonNullExample(@NonNull Person person) {
    super("Hello");
    this.name = person.getName();
  }
}

Vanilla Java

import lombok.NonNull;

public class NonNullExample extends Something {
  private String name;
  
  public NonNullExample(@NonNull Person person) {
    super("Hello");
    if (person == null) {
      throw new NullPointerException("person is marked @NonNull but is null");
    }
    this.name = person.getName();
  }
}

 

728x90

'Library' 카테고리의 다른 글

Lombok features - @EqualsAndHashCode  (0) 2020.12.21
Lombok features - @ToString  (0) 2020.12.21
Lombok features - @Getter and @Setter  (0) 2020.12.21
Lombok features - @Cleanup  (0) 2020.12.09
Lombok features - val & var  (0) 2020.12.09
Comments