Using @ToString annotation

In this post under Lombok, I will show with example the purpose of @ToString annotation and how to use it.

This annotation is applied at class level.

When applied it instructs Lombok to consider all the non-static fields in a class and generate a “toString” function.

When the output of Lombok generated “toString” function is printed on the console. We will get the below output.

    MyClass(foo=123, bar=234)

where “MyClass” is the class name, “foo” and “bar” are the field names, and “123” and “234” are field values.

Below code shows an example of how to use the annotation

package package5;

import lombok.ToString;

public class Person {
    private String firstName;
    private String middleName;
    private String lastName;
    private int age;

    public Person(String firstName, String middleName, String lastName, int age) {
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
        this.age = age;

In the above code, we have applied the “@ToString” annotation at the class level.

Below is the main class that uses the above pojo class

Main class

package package5;

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

In the above code, we are creating an instance of Person object.

In the next line, we are printing it to the console. This code will internally call the Lombok generated “toString” method and below output will be printed.


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

Leave a Reply