callSuper = true

package com.yx;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

public class App {


    public static void main(String[] args)  {
        User user = new User();
        user.setName("小红");
        user.setAge(10);
        user.setHobby("dance");
        test(user);
    }
    public static void test(Person person) {
        // 使用传入对象的toString方法,如果传入的是子类对象,则调用子类的toString方法,
        // 子类的@ToString若是没有添加callSuper=true,则不会打印出基类的属性
        System.out.println(person);

        System.out.println("---------------------------------------");

        // 打印出传入对象的所有属性,即使@ToString没有添加callSuper=true
        System.out.println(JSON.toJSONString(person));
    }
}

@Data
@ToString
class Person {
    private String name;
    private Integer age;
}

@Data
@EqualsAndHashCode(callSuper = true) // equal和hashCode方法里会调用基类的对应方法
@ToString(callSuper = true) // toString方法里会调用基类的对应方法
class User extends Person {
    private String hobby;
}

打印结果:

User(super=Person(name=小红, age=10), hobby=dance)
---------------------------------------
{"age":10,"hobby":"dance","name":"小红"}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值