Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore property when generating equals and hashcode

Tags:

Let's say I have a class Customer:

public class Customer {

private String firstName;
private String lastName;
private String doNotAddMeToEquals;

//Getters and Setters below

}

I'm using the Guava Eclipse Plugin in Eclipse to generate my equals() and hashCode() methods; however, I could just as well use the eclipse -> Source -> Generate HashCode / Equals. Either way...doesn't matter.

Is there a way to Annotate property doNotAddMeToEquals such that when I generate the equals & hashcode methods with the guava plugin that property doesn't show in the list?

Without altering the plugin or creating a template.

Thanks in Advance!!

like image 930
Jason McD Avatar asked Oct 21 '13 22:10

Jason McD


People also ask

Do we need to override both hashCode and equals method?

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object. hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

How do you override hashCode and equals method?

if a class overrides equals, it must override hashCode. when they are both overridden, equals and hashCode must use the same set of fields. if two objects are equal, then their hashCode values must be equal as well. if the object is immutable, then hashCode is a candidate for caching and lazy initialization.

Does @data generate equals and hashCode?

The annotation @Data with inheritance produces the next warning: Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.

How do you override equals method in Lombok?

If you need to write your own equals methods, you should always override canEqual if you change equals and hashCode . NEW in Lombok 1.14. 0: To put annotations on the other parameter of the equals (and, if relevant, canEqual ) method, you can use onParam=@__({@AnnotationsHere}) . Be careful though!


2 Answers

It sounds like what you want is something like this:

http://projectlombok.org/features/EqualsAndHashCode.html

It lets you use annotations to drive what properties are included in the equals and hashcode methods.

like image 81
aet Avatar answered Sep 17 '22 14:09

aet


Using Lombok you can exclude properties from hashcode and equals like such as:

@EqualsAndHashCode(exclude = {"nameOfField"})

That would be in your case

@EqualsAndHashCode(exclude = {"doNotAddMeToEqualsAndHashCode"})
like image 41
i-tms Avatar answered Sep 19 '22 14:09

i-tms