Tuesday, June 30, 2009

Apache Commons Lang: Builders Example

While it's been around for a while (version 1.0 was released in 2002), I recently discovered Apache Commons Lang and its various Builders that help make writing equals(), hashCode, and toString() much simpler.

To quote the project's homepage:

The standard Java libraries fail to provide enough methods for manipulation of its core classes. The Lang Component provides these extra methods.

Here's a simple object with two properties that demonstrates how to use some of the Builders:

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Person {

String name;
Integer age;

Person(String name, Integer age) {
this.name = name;
this.age = age;

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

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

public String toString() {
return ToStringBuilder.reflectionToString(this);
An example use of the overriden methods in Groovy:
    def person = new Person("Costanza", 35)
println "String: $person"
println "Hash Code: " + person.hashCode()

def samePerson = new Person("Costanza", 35)
def differentPerson = new Person("Newman", 35)
println "Same equals(): " + person.equals(samePerson)
println "Different equals(): " + person.equals(differentPerson)
    String: Person@6bb36[name=Costanza,age=35]
Hash Code: -422159695
Same equals(): true
Different equals(): false
An alternative to ToStringBuilder is ReflectionToStringBuilder:
    import org.apache.commons.lang.builder.ReflectionToStringBuilder;
public String toString() {
return ReflectionToStringBuilder.toString(this);

For String building, there are also various styles you can pass to the builder's constructor: String Styles.

There's also a CompareToBuilder that I have yet to play with.

No comments:

Post a Comment