Friday Sep 06


PDF Print E-mail
Monday, 25 April 2011 15:06
AddThis Social Bookmark Button

Apache Commons EqualsBuilder

The first builder I want to discuss is the EqualsBuilder . This class, as you can probably guess, helps you to define an equals algorithm for your object. Let's say we had a class like this:
Java equals tutorial

public class Person {
	private long id;
	private String firstName;
	private String lastName;

Here is how we would use the EqualsBuilder class to process whether or not two instances of this class are equal (taken from the Javadocs):

Java EqualsBuilder equals

	public boolean equals(Object object) {
		if (!(object instanceof Person)) {
			return false;
		Person rhs = (Person) object;
		return new EqualsBuilder()
			.append(firstName, rhs.firstName)
			.append(lastName, rhs.lastName)

This particular builder doesn't drastically save time from the normal implementation, with the exception of the fact that it automatically handled array equality (looping and checking element equality). Note the use of 'appendSuper' - this method accounts for superclass values. You'll see this in the other builders as well.

Alternatively, you can use the reflection-based static methods:

Java tutorial Equals builder reflection

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

This method of implementing the equals algorithm has two drawbacks, however - 1) it is potentially much slower because it uses reflection, and 2) It uses field accessibility modification, so it will fail in security-restricted JVMs. For rapid prototyping, however, it is a good tool to be aware of.

Tags: field , equals , class , equalsbuilder , algorithm , reflection , slower , accessibility

Add comment

Security code

Java Tutorial on Facebook