Thursday, July 19, 2007

Lang for the Commons

I had to deal today with a class that contains an attribute of type java.io.Serializable. When I asked Eclipse to generate the equals and hashCode methods that I needed to be implemented, it warned me that the generated code will not work properly because Serializable does not mandate anything in term of implementation of these two methods.

And as expected, I started to get red lights when my test cases were stuffing byte[] in the Serializable attribute: the hash computation and equality algorithm used for this type was simply not working and two instances of my object containing the same sequence of bytes in two different byte arrays were bound to be different.

Since I was already Commons Lang for building the String representation of my object, I thought I should give a shot at the hashcode and equals builder it offers. Reading no doc and proceeding only by analogy with the toString method, I quickly typed this:

public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}

public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}

And it worked immediately! Not only it saved me a lot of lines of code but it worked exactly as I expected from the look at the name of the classes and the methods.

Nice API, nice library: you need it.