SoFunction
Updated on 2025-03-03

Interpretation of @Data annotation of parent-child inheritance

@Data annotation of parent-child class inheritance issues

When all parent class subclasses use @Data annotation, it will cause: the equals method overrides equals in the parent class, which may not be symmetric. question.

Solution

Add the following annotation to the subclass

@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)

When using @Data, the default state of @equalsandhashcode is calledsuper=false

  • @equalsandhashcode(callsuper=false) is expressed as if the members in the parent class are not considered when comparing objects. Just compare the properties in the subclass to determine whether they are the same.
  • @equalsandhashcode(callsuper=true) will consider the members in the parent class when comparing, and determine whether the same is done by the attributes in the parent class and the child class.

After adding @Data to subclass, "appear" when IDEA debugging, the parent class attribute has no value

Project Scenario

When self-testing a function, IDEA debugged VIEW of the same object to view the object content and found that the properties of the parent class in the return subtype with @Data did not appear.

Problem description

// Return VO object in parent class Response 
@Data
public class PVO{
 
    private Sting serialNum;
}
 
 
// Subclasses expand parent class attributes@Data
public class SVO extends PVO{
 
    private Sting userName;
}

The interface returns the object as SVO. When the code clicks VIEW during the debug code process, the parent class attribute does not appear.

Cause analysis

In fact, the content of the viewing object with the same VIEW is displayed according to the object's toString() method. When both the subclass and the parent class use the @Data annotation, the subclasses toString, equal and toHash will not bring the properties of the parent class in, resulting in the parent class method not appearing when the same VIEW.

Solution

1. When debugging, it is accurate to view the object's property values ​​in the IDEA console;

2. If you have to use VIEW to view it, add the following annotations to the subclass, so that the parent class method will be introduced.

@ToString(callSuper = true)

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.