In this post under Lombok, I will show with example the purpose of “rank” attribute in “ToString.Include” annotation.
Whenever we use “ToString” annotation on a class, it generates the string format of an object with fields displayed in the order they are declared in the class.
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 snippet. The fields of the object are displayed in the order they are declared in the class.
We can change this order by taking help of “ToString.Include” annotations “rank” attribute as shown below java code
Person
1 package package9;
2
3 import lombok.ToString;
4
5 @ToString(onlyExplicitlyIncluded = true)
6 public class Person {
7 @ToString.Include(rank = 1)
8 private String firstName;
9
10 @ToString.Include(rank = 2)
11 private String middleName;
12
13 @ToString.Include(rank = 3)
14 private String lastName;
15
16 @ToString.Include(rank = 4)
17 private int age;
18
19 public Person(String firstName, String middleName, String lastName, int age) {
20 super();
21 this.firstName = firstName;
22 this.middleName = middleName;
23 this.lastName = lastName;
24 this.age = age;
25 }
26 }
In the above code, we have added “ToString.Include” annotation to all the fields. In addition to that we also set “rank” attribute to an integer value. Refer to line 7, 10, 13, 16.
The “rank” attribute takes a value of type Integer and fields with higher rank are printer first.
So in our case, “age” field will be printed first followed by “lastName”, “middleName”, and “firstName” as shown below.
Person(age=39, lastName=lName, middleName=mName, firstName=fName)
In this way, we can use the “rank” attribute to change the display order of class fields.