问题复现
@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源代码;