Lombok 어노테이션

라따뚜이·2022년 4월 3일
0

lombok

목록 보기
1/1

@NonNull

null을 체크해준다.

@NonNull 변수 앞에 붙이면 자동으로 null-check를 해주며
해당 변수의 value가 null인 경우 NullPointerException예외를 발생시킨다. 아래 공식 홈페이지 글을 읽어보자~

lombok site


import lombok.NonNull;

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

Lombok 사용 시


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();
  }
}

Vanilla Java





@NoArgsConstructor

매개변수가 없는 생성자를 생성한다.

fields(변수)들이 final로 선언된 경우 compiler error가 발생한다. 이럴 경우 @NoArgsConstructor(force = true)로 선언한다. value = 0 / false / null로 초기화된다.


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;
  }
}

With 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() {
    }
  }
}

Vanilla Java





@RequiredArgsConstructor

초기화 되지 않은 final fields, @NonNull가 마크되어 있는 모든 field에 대한 생성자들을 자동으로 생성해주면 @NonNull가 마크되어 있으면 null-check까지 해준다.





@AllArgsConstructor

class의 모든 멤버 변수를 매개변수로 받는 생성자를 구현





Data

class 맴버 변수의 Getter/Setter 메서드를 구현해준다.





*** 해당 lombok어노테이션을 사용하거나 이클립스나 인텔리제이에서 지원하는 단축키를 사용해서 생성할 수도 있다.
아니면 직접 하나하나 코드를 작성하거나 ㅠㅜㅠ

lombok 홈페이지

profile
돈만 준다면 해 노예

0개의 댓글