Using @ToString.Exclude annotation

In previous post under Lombok you learned about “@ToString” annotation.

It is an annotation that when applied at the class level generates a “toString” method.

The “toString” method generated by Lombok considers all the non-static fields in the class.

In this post under Lombok, I will show with example how to override this default behavior.

We can override this default behaviour, in other words, we can instruct Lombok to ignore certain non-static fields when generating the “toString” method.

To achieve this we will add another annotation “@ToString.Exclude” in conjunction with “@ToString” annotation.

This new annotation is applied at the field level and instructs Lombok to ignore the annotated field when generating the “toString” method.

Below is an example of it

1  package package6;
3  import lombok.ToString;
5  @ToString
6  public class Person {
7      private String firstName;
8      private String middleName;
9      private String lastName;
10     @ToString.Exclude
11     private int age;
13     public Person(String firstName, String middleName, String lastName, int age) {
14         super();
15         this.firstName = firstName;
16         this.middleName = middleName;
17         this.lastName = lastName;
18         this.age = age;
19     }
20 }

In the above pojo class, at line 5 we have applied “@ToString” annotation at the class level instructing Lombok to generate a “toString” method considering all the
non-static fields.

At the same time, at line 10, I apply “@ToString.Exclude” annotation to the “age” field. Instructing Lombok to not consider “age” field when generating “toString” method.

As a result of which, we get a “toString” method which will consider all the fields in the “Person” class except “age” field.

Below is the main class code that will instantiate the “Person” class and prints it to the console.

Main class

package package6;

public class Example6 {
    public static void main(String[] args) {
        Person person = new Person("fName", "mName", "lName", 39);

Below is the output. As you see from the output “age” field value is ignored when printing to console.


    Person(firstName=fName, middleName=mName, lastName=lName)

In this way, we can instruct the Lombok to ignore certain fields when generating “toString” method for a class.

Leave a Reply