Sobes.tech
Junior — Middle

What requirements and recommendations should be considered when automatically generating an equals method with Lombok?

sobes.tech AI

Answer from AI

When automatically generating the equals method with Lombok (for example, using the @EqualsAndHashCode annotation), the following points are important:

  • Choosing fields for comparison: Lombok by default includes all non-static fields of the class. If you need to exclude certain fields (for example, fields that do not affect equality logic), use the exclude parameter.
  • Calling super.equals: If the class inherits from another, you can specify callSuper = true to include the comparison of superclass fields.
  • Consistency with hashCode: Usually, equals and hashCode should be generated together to adhere to the contract. Lombok generates both when using @EqualsAndHashCode.
  • Handling cyclic references: Lombok can correctly handle cyclic references, but in complex cases, it is worth verifying correctness.

Example usage:

import lombok.EqualsAndHashCode;

@EqualsAndHashCode(exclude = {"id"}, callSuper = false)
public class Person {
    private String name;
    private int age;
    private String id; // does not participate in equals
}