1. Possible problems
This class defines an equals method that overrides the equals method in the parent class.
Both equals methods use instanceof to determine whether the two objects are equal.
This is full of dangers, because it is important that the equals method is symmetric (in other words, (b) == (a)).
If B is a subtype of a, and the equals method of a checking parameter is an instance of a and the equals method of B checking parameter is an instance of B, it is very likely that the equivalent relationship defined by these methods is not symmetric.
2. Solution
In Java,@EqualsAndHashCode(callSuper = true)
It is an annotation provided by the Lombok library to simplify generationequals()
andhashCode()
Code of the method.
This annotation is usually used on entity classes or classes that need to implement these two methods correctly.
@EqualsAndHashCode
Detailed explanation of the annotation:
-
equals()
Method: Used to compare whether two objects are equal. According to which fields in the class, we can use this annotation to determine whether the objects are equal. -
hashCode()
Method: When two objects passequals()
When the method determines that they are equal,hashCode()
The method must return the same value. This can also be configured through this annotation.
callSuper
The function of parameters:
-
callSuper = true
: This means that it is generatedequals()
andhashCode()
The corresponding method of the parent class (superclass) will be called inside the method. - This means subclasses
equals()
andhashCode()
A method inherits the behavior defined in the parent class and takes into account the fields declared in the parent class.
For example:
Suppose you have a base classBaseClass
and a subclass inherited from itSubClass
, and you want to be inSubClass
In-houseequals()
andhashCode()
Methods can also be consideredBaseClass
fields inSubClass
Use on@EqualsAndHashCode(callSuper = true)
。
3. Sample code
public class BaseClass { private int id; // Constructor, getter and setter omit...} @EqualsAndHashCode(callSuper = true) public class SubClass extends BaseClass { private String name; // Constructor, getter and setter omit... }
In this example:
ifBaseClass
Also used Lombok@EqualsAndHashCode
Annotation, thenSubClass
ofequals()
andhashCode()
Methods will be consideredBaseClass
In-houseid
Fields andSubClass
My ownname
Field.
If notcallSuper = true
,SoSubClass
The method will only considername
Fields, and ignoreBaseClass
any field in .
4. Suggestions
Generally, most of them use Lombok, mainly because of its automatic generation of Get and Set methods.
You can directly use @Getter and @Setter to avoid spreading, resulting in unnecessary problems.
Note: If there is a cast in the code, you need to add a full parameter constructor.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.