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

问题复现

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

  • 8
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@EqualsAndHashCode(callSuper = true)注解用于子类对象之间进行比较时,会将父类对象的属性也考虑在内,根据父类和子类共同的属性进行比较。这样可以确保子类对象在比较时能够正确地考虑到父类对象的属性。 @ToString(callSuper = true)注解会将父类中的属性也包含在生成的toString方法中。这样可以确保在打印子类对象时,能够同时打印出父类对象的属性。 以下是一个示例代码,演示了@EqualsAndHashCode(callSuper = true)和@ToString(callSuper = true)的使用: ```java import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @Data class Parent { private String parentProperty; } @Data @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) class Child extends Parent { private String childProperty; } public class Main { public static void main(String[] args) { Parent parent = new Parent(); parent.setParentProperty("Parent Property"); Child child1 = new Child(); child1.setParentProperty("Parent Property"); child1.setChildProperty("Child Property"); Child child2 = new Child(); child2.setParentProperty("Parent Property"); child2.setChildProperty("Child Property"); System.out.println(child1.equals(child2)); // 输出:true System.out.println(child1.toString()); // 输出:Child(parentProperty=Parent Property, childProperty=Child Property) } } ``` 在上述示例中,Child类继承自Parent类,并使用了@Data、@EqualsAndHashCode(callSuper = true)和@ToString(callSuper = true)注解。通过equals方法比较两个Child对象时,会同时考虑到父类对象的属性。在打印Child对象时,会同时打印出父类对象的属性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值