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)
@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
.
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); } }
ToString
annotations.Person
class annotated with @AllArgsConstructor
and @ToString
annotations.age
field.name
field annotated with @ToString.Exclude
.address
field.Person
class.The string representation of the person instance contains all fields except name
.