How to exclude fields in the @ToString annotation in Lombok

Overview

The @ToString annotation is one of the annotations in the project Lombok.

Note: Refer to What is the @ToString annotation in Lombok? for the introduction of the annotation.

The @ToString annotation generates an implementation for the toString() method where the class name, along with each field in order, separated by commas, is printed. But sometimes, there is a need to exclude only specific fields in the string representation of the fields.

For example, consider a Person class with three attributes - name, age, and address.

@ToString
@AllArgsConstructor
class Person {
      private int age;
      private String name;
      private String address;
}

We define an instance of the Person class:

Person person = new Person(30, "sam", "US");

The default string representation of the object above is as follows:

Person(age=30, name=sam, address=US)

All the fields are present in the output. What if we don’t want specific fields in the output and we want to only exclude the name field?

Person(age=30, address=US)

The @ToString.Exclude and onlyExplicitlyIncluded annotation

@ToString.Exclude indicates which fields have to be excluded in the string representation of the object. To exclude a field annotate the respective field with @ToString.Exclude.

Code

Let’s look at the code below:

import lombok.AllArgsConstructor;
import lombok.ToString;

public class Main {

    @AllArgsConstructor
    @ToString
    static class Person {

        private final int age;

        @ToString.Exclude
        private final String name;

        private final String address;
    }


    public static void main(String[] args) {
        Person person = new Person(30, "sam", "US");
        System.out.println("Person object - " + person);
    }
}

Explanation

  • Lines 1 and 2: We import the AllArgsConstructor and ToString annotations.
  • Lines 6 to 8: We define the Person class annotated with @AllArgsConstructor and @ToString annotations.
  • Line 10: We define the age field.
  • Lines 12 and 13: We define the name field annotated with @ToString.Exclude.
  • Line 15: We define the address field.
  • Line 20: We create an instance of the Person class.
  • Line 21: We print the person instance created in line 20 to console.

The string representation of the person instance contains all fields except name.

Free Resources