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)
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
.
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); } }
ToString
annotations.Person
class annotated with @AllArgsConstructor
and @ToString
annotations. We pass onlyExplicitlyIncluded = true
to indicate Lombok to generate output for the fields annotated with @ToString.Include
only.age
field.name
field annotated with @ToString.Include
.address
field annotated with @ToString.Include
.Person
class.person
instance created in line 22.The string representation of the person
instance contains only name
and address
.