This was my response to this short post about using reflectionHashCode to implement your objects hashCode method dzone.com – overriding equals() and hashcode() – best practice
I’ve come to love the Apache commons builders over the last couple of years and use them where possible. They avoid a lot of boilerplate.
Wanted to raise something with regard to the hashcode builder. Today I watched a webinar, ‘Hash hash, away it goes’ (http://www.javaspecialists.eu/webinars/ and also described in text here: http://www.javaspecialists.eu/archive/Issue031.html) which was about writing hash code methods on your objects and using them as key objects in your HashMaps – and what happens when they arent written properly causing elements to not be retrieved from the map!
One of the summary points of this article was that hashCode methods should be as fast as possible and one of the participants asked about the apache commons reflection hashcode builder. Because the reflectionHashCode uses reflection it wont be the fastest possible implementation possible that you can write, so if you are concerned about performance, then you should consider using the other non-static implementation of HashCodeBuilder (granted not so dynamic). The javadoc for HashCodeBuilder (http://commons.apache.org/lang/api/org/apache/commons/lang/builder/HashCodeBuilder.html) mentions reflection is slower than testing explicitly.
One thing you could do is if using dynamic fields though (say in a language like Groovy that allows fields added at runtime) is consider the fields which are immutable identity fields and have your hashcode builder just combine the hashcodes for those. Presumably (and its a big presumption), your fields that are being added dynamically arent immutable and arent defining the identity of the object. So the question is, do you really need to add those fields to your hashcode method in the first place? You could then just define a hashcode builder on the immutable id fields that are in the base class and it shouldnt change how your HashSets and Maps behave regardless of dynamic fields added. But if your new fields are added from subclasses to a parent domain, there is the appendSuper method on the HashCode builder