Lombok Annotations Note

December 22, 2022

Overview

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

Project Lombok is a library that could greatly reduces the amount of boilerplate code in Java projects. This post records serveral common used annotations for use when writing Java code.

Annotations

@NonNull

This annotation generates the null check code and inserts at the very top of your method.

For constructors, the null-check will be inserted immediately following any explicit this() or super() calls. For record components, the null-check will be inserted in the 'compact constructor' (the one that has no argument list at all), which will be generated if you have no constructor.

import lombok.NonNull;

public class Example {
  private String name;

  public Example(@NonNull String name) {
    /* Null check code goes here.
    if (name == null) {
      throw new NullPointerException("name is marked non-null but is null");
    }
    */
    this.name = name
  }
}

https://projectlombok.org/features/NonNull

@Getter and @Setter

This annotation generates the default getter and setter, i.e. getFoo(), setFoo(), isFoo() (if the type is Boolean).

import lombok.Getter;
import lombok.Setter;

public class Example {
  @Getter @Setter private int age = 10;

  /*
  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }
  */
}

https://projectlombok.org/features/GetterSetter

@ToString

This annotation generates an implementation of the toString() method.

import lombok.ToString;

@ToString
public class Example {
  private String name;
  private int age;

  /*
  public toString() {
    return "Example(name=" + this.getName() + ", age=" + this.getAge() + ")"; 
  }
   */
}

@EqualsAndHashCode

This annotation generates implementations of the equals(Object other) and hashCode() methods.

https://projectlombok.org/features/EqualsAndHashCode

@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor

  • @NoArgsConstructor will generate a constructor with no parameters.
  • @RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling.
  • @AllArgsConstructor generates a constructor with 1 parameter for each field in your class.

https://projectlombok.org/features/constructor

@Data

A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor.

https://projectlombok.org/features/Data

Reference