Friday, 24 February 2012

Overriding equals and hashCode with Guava and Objects class

We usually use IDE to override equals and hashCode methods in our classes.
Let's see how IntelliJ IDEA 11 copes with a simple class with 3 fields:
Even though the class seems simple, the methods' size is a little bit scary.
Using EqualsBuilder and HashCodeBuilder from Apache Commons Lang makes the methods much smaller, however introduces one major flaw: it uses reflection, which isn't a speed demon.
To the rescue comes Guava, which makes these methods simpler and more readable:
If you're working on a project in which you can use Java 7, it provides a similar solution without having to use any external library:
At the time of writing this, IDEA 11 doesn't support generating equals and hashCode using Guava or Objects class from Java 7. I created a plugin that provides such possibility:
http://plugins.intellij.net/plugin/?idea&id=6875

No comments:

Post a Comment