How to include fields in the @ToString annotation in Lombok
Overview
The @ToString annotation is one of the annotations in the project Lombok.
Note: Refer 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 include only specific fields in the string representation of the fields.
For example, consider a Person class that has 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 above object is as follows:
Person(age=30, name=sam, address=US)
All the fields are present in the output. What if we want only specific fields in the output?
and we want to print the name field only:
Person(name=sam)
@ToString.Include and onlyExplicitlyIncluded
onlyExplicitlyIncluded is a boolean parameter of the @ToString annotation that indicates whether to choose fields that are included explicitly.
@ToString.Include indicates which fields have to be included in the string representation of the object. To include a field or the output of an instance method, annotate the respective field or method with @ToString.Include.
Code
Let’s look at the code below:
import lombok.AllArgsConstructor;
import lombok.ToString;
public class Main {
@AllArgsConstructor
@ToString(onlyExplicitlyIncluded = true)
static class Person {
private final int age;
@ToString.Include
private final String name;
@ToString.Include
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
ToStringannotations. - Lines 6 to 8: We define the
Personclass annotated with@AllArgsConstructorand@ToStringannotations. We passonlyExplicitlyIncluded = trueto indicate Lombok to generate output for the fields annotated with@ToString.Includeonly. - Line 10: We define the
agefield. - Lines 13 and 14: We define the
namefield annotated with@ToString.Include. - Lines 16 and 17: We define the
addressfield annotated with@ToString.Include. - Line 22: We create an instance of the
Personclass. - Line 23: We print the
personinstance created in line 22.
The string representation of the person instance contains only name and address.