问题复现
@data
public class people {
private string height;
private string weight;
}@data
public class student extends people {
private string name;
}public class test {
public static void main(string[] args) {
student student = new student();
student.setheight("180cm");
student.setweight("65kg");
student.setname("jack");
system.out.println(student.tostring());
}
}运行代码后,打印如下:
student(name=jack)
root cause
如果domain中没有重写tostring, 且使用了@data注解, 调用tostring时只会打印子类本身的属性值, 如果想要打印父类的属性:
- 方式一:重写tostring
- 方式二:子类加上@data和@tostring(callsuper = true)两个注解, 父类也使用注解@data
解决方案
@data
@tostring(callsuper = true)
public class student extends people {
private string name;
}行代码后,打印如下:
student(super=people(height=180cm, weight=65kg), name=jack)
lombok 使用@data时会重写tostring(),查看@data源代码;

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论