In this post under lombok. I will explain the purpose and how to use “@EqualsAndHashCode.Include” annotation.
In previous post “Using @EqualsAndHashCode.Exclude” I introduced you to “@EqualsAndHashCode.Exclude” annotation.
Using “@EqualsAndHashCode.Exclude” annotation we are telling Lombok which fields should not be considered when generating “equals” and “hashCode” method of a POJO class.
Now “@EqualsAndHashCode.Include” is reverse of “@EqualsAndHashCode.Exclude”.
Using “@EqualsAndHashCode.Include” annotation we are telling what fields to consider when generating “equals” and “hashCode” method of POJO class.
Similar to “@EqualsAndHashCode.Exclude” this is also used in combination with “@EqualsAndHashCode” annotation with one change, we need to set “@EqualsAndHashCode”‘s attribute
“onlyExplicitlyIncluded” to true.
Below is an example
POJO class
1 package package13;
2
3 import lombok.EqualsAndHashCode;
4
5 @EqualsAndHashCode(onlyExplicitlyIncluded = true)
6 public class Person {
7 @EqualsAndHashCode.Include
8 private String firstName;
9 @EqualsAndHashCode.Include
10 private String middleName;
11 @EqualsAndHashCode.Include
12 private String lastName;
13 private int age;
14
15 public Person(String firstName, String middleName, String lastName, int age) {
16 this.firstName = firstName;
17 this.middleName = middleName;
18 this.lastName = lastName;
19 this.age = age;
20 }
21 }
In the above POJO class, at line 5, I have applied “@EqualsAndHashCode” annotation at class level and also set its attribute “onlyExplicitlyIncluded” to true.
Next we have applied “@EqualsAndHashCode.Include” on all the fields (except “age” field) that has to be considered when generating “equals” and “hashCode” methods.
Below is the main code that uses the above POJO class
Main class
package package13;
public class Example13 {
public static void main(String[] args) {
Person person1 = new Person("Elvis", "M", "Emmerson", 39);
Person person2 = new Person("Elvis", "M", "Emmerson", 30);
System.out.println("person1 equals person2: " + person1.equals(person2));
}
}
In the main code, we have created two person objects with similar firstName, middleName, and lastName but different age but still both will be equals.
In other words the “equals” method will return true.
In this way we can use “@EqualsAndHashCode.Exclude” annotation.
Below is the output
Output
person1 equals person2: true