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, the names of the fields need to be different 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 above object is as follows:
Person(age=30, name=sam, address=US)
The names of the fields are as defined in the class. If we want to change the names of the fields while printing, we do as follows:
Person(Username=sam, Country=US, Age=30)
name
parameterThe name
parameter of the Include interface of the ToString
annotation is used to give a different name to fields in the string representation.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>test</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>Main</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
Lines 1 and 2: We import the AllArgsConstructor
and ToString
annotations.
Lines 6 to 8: We define the Person
class annotated with @AllArgsConstructor
and @ToString
annotations.
Lines 10 and 11: We define the age
field with Age
.
Lines 13 and 14: We define the name
field with Username
.
Lines 16 and 17: We define the address
field with Country
.
Line 22: We create an instance of the Person
class.
Line 23: We print the person instance created in line 22 to console.