Using @ToString.Include annotation

In previous posts under Lombok, I showed you how to use “@ToString” and “@ToString.Exclude” annotations.

In this post, I will show with example how to use “@ToString.Include” annotation.

This annotation is inverse of “@ToString.Exclude”.

This annotation is also used in conjunction with “@ToString” annotation. We also need to enable “onlyExplicitlyIncluded” attribute.

This annotation is also applied at field level.

This annotation instructs Lombok to include the annotated field.

Below is an example of pojo class which uses both “@ToString” and “@ToString.Include”.

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

In the above code, at line 5, I have applied the “@ToString” annotation to the “Person” class with “onlyExplicitlyIncluded” attribute enabled. This attribute has to
be enabled for the “@ToString.Include” annotation to work.

Then I added “ToString.Include” annotation to all the fields of the class except “age” field.

As a result all the other fields of the “Person” class will be included when generating the “toString” method excluding “age” field.

Below is the main class for your reference

Main class

package package7;

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

In the above main class, we are creating an instance of “Person” class and printing it to console.

Below is the output


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

As you can see from the output “age” field is not printed.

In this way we can instruct Lombok to include specific fields of a class when generating “toString” method.

Leave a Reply