In this post under Lombok, I will explain the purpose of and how to use “callSuper” attribute available in “@ToString” annotation.
This attribute comes into picture when we are working with hierarchy of classes.
For example lets say class “Shape” is a super class and class “Square” is a subclass of “Shape” class.
“Shape” and “Square” class both has a “toString” method.
Now when we execute “toString” method on “Square” class it prints fields only from “Square” class.
But “Square” is a class made up of fields available in it and also fields available in super class which is “Shape” class.
Printing fields only from “Square” class is not correct, we have to include fields from its super “Shape” class.
To do that, we enable the “callSuper” attribute in the “@ToString” annotation.
Below is the code of three class “Shape”, “Square”, and “Rectangle”. “Square” and “Rectangle” extends “Shape” class.
Shape
package package8;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class Shape {
protected float area;
}
In the above class, “@ToString” annotation is applied to “Shape” class.
Square
1 package package8;
2
3 import lombok.Getter;
4 import lombok.Setter;
5 import lombok.ToString;
6
7 @Getter
8 @Setter
9 @ToString(callSuper = true)
10 public class Square extends Shape {
11 private int x;
12
13 public Square(int x) {
14 super();
15 this.x = x;
16 this.area = x * x;
17 }
18 }
In the above code, “Square” class extends “Shape” class and to include fields from super class in “toString” method, we have to added “ToString” annotation at the class
level with “callSuper” attribute enabled.
Rectangle
1 package package8;
2
3 import lombok.Getter;
4 import lombok.Setter;
5 import lombok.ToString;
6
7 @Getter
8 @Setter
9 @ToString
10 public class Rectangle extends Shape {
11 private int x;
12 private int y;
13
14 public Rectangle(int x, int y) {
15 super();
16 this.x = x;
17 this.y = y;
18 this.area = x * y;
19 }
20 }
In the code, “Rectangle” class extends “Shape” class. We also added “@ToString” annotation at class level but disabled “callSuper” attribute.
Now we will use all three class in the below main class.
Main class
package package8;
public class Example8 {
public static void main(String[] args) {
Square square = new Square(5);
Rectangle rectangle = new Rectangle(5, 10);
System.out.println(square);
System.out.println(rectangle);
}
}
In the above main class, I have created instances of “Shape” and “Rectangle” class and printed them to the console.
Below is the output
Output
Square(super=Shape(area=25.0), x=5)
Rectangle(x=5, y=10)
As you can see from the output, since “callSuper” attribute is enabled for “Square” class it prints super class information also, but for “Rectangle” class lombok
excludes the super class information.
In this way we can instruct Lombok whether or not to include super class “toString” information when printing sub class “toString” information.