Changing display name when printing string format of an object

In this post under Lombok, I will show with example, the purpose of “name” attribute in “ToString.Include” annotation.

Whenever we use “ToString” annotation on a class, it generates the string format of an object where field name (also can be called as display name) are equal to object property name.

So for example if below is the class that we are using

Person


package package9;

import lombok.ToString;

@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) {
        super();
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
        this.age = age;
    }
}

The output of “toString” method will be as shown below


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

As shown in the above output, the field names (i.e., display names) matches the property names.

We can change this default behavior by using “name” attribute available in “ToString.Include” annotation as shown below

Person


1  package package10;
2  
3  import lombok.ToString;
4  
5  @ToString(onlyExplicitlyIncluded = true)
6  public class Person {
7      @ToString.Include
8      private String firstName;
9      @ToString.Include
10     private String middleName;
11     @ToString.Include(name = "surname")
12     private String lastName;
13     @ToString.Include
14     private int age;
15     
16     public Person(String firstName, String middleName, String lastName, int age) {
17         super();
18         this.firstName = firstName;
19         this.middleName = middleName;
20         this.lastName = lastName;
21         this.age = age;
22     }
23 }

In the above code, we have added “ToString.Include” annotation at all the fields.

In addition to that, at line 11, we have used “name” attribute to change the display name.

We changed the field display name from “lastName” to “surname”. The output will be as shown below


    Person(firstName=Elvis, middleName=M, surname=Emmerson, age=39)

In this way, we can use the name attribute in “ToString.Include” annotation to change display name.

Leave a Reply