当前位置: 代码网 > it编程>编程语言>Java > Java之注解@Data和@ToString(callSuper=true)解读

Java之注解@Data和@ToString(callSuper=true)解读

2024年11月06日 Java 我要评论
问题复现@datapublic class people { private string height; private string weight;}@datapublic class

问题复现

@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源代码;

总结

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

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com