@ToString(callSuper = true)
时间: 2023-10-26 18:02:55 浏览: 147
java中lombok的@Data引发问题详解
5星 · 资源好评率100%
This is a Java annotation that can be used to generate a `toString` method in a class. The `callSuper` attribute is set to `true`, which means that the generated `toString` method will also include the output of the `toString` method of its superclass (if it has one).
For example, consider the following class hierarchy:
```
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
@Override
public String toString() {
return "Animal{name='" + name + "'}";
}
}
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name);
this.breed = breed;
}
@Override
public String toString() {
return "Dog{breed='" + breed + "', " + super.toString() + "}";
}
}
```
If we create a `Dog` object and call its `toString` method, we would get:
```
Dog{breed='Labrador', Animal{name='Buddy'}}
```
This is because the `Dog` class overrides the `toString` method of its superclass (`Animal`), and includes the output of the `Animal` class's `toString` method by calling `super.toString()` and concatenating it with the `breed` attribute.
If we annotated the `Dog` class with `@ToString(callSuper = true)`, Lombok would generate the `toString` method for us, which would be equivalent to the one we manually wrote above:
```
@ToString(callSuper = true)
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name);
this.breed = breed;
}
}
```
阅读全文