Showing posts with label using reflection. Show all posts
Showing posts with label using reflection. Show all posts

Sunday, 15 May 2011

Implementing compareTo() using commons-lang

Here CompareToBuilder is used to implement compareTo();

public int compareTo(Person person) {
return new CompareToBuilder()
append(this.firstName, person.firstName)
append(this.lastName, person.firstName)
toComparison();
}


Also, there is yet another reflection option:


public int compareTo(Object o) {
return CompareToBuilder.reflectionCompare(this, o);
}

Saturday, 14 May 2011

Implementing hashCode using commons-lang

This example shows how to implement hashCode() using HashCodeBuilder of commons-lang.

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

import java.io.Serializable;

public class MyClass implements Serializable {
private Long id;

private String title;

private String author;

public int hashCode() {
return new HashCodeBuilder().append(id).append(title).append(author).toHashCode();

// return HashCodeBuilder.reflectionHashCode(this);

}
}

 

Also, reflection can be used to implement the same function:


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