tags:

views:

1586

answers:

4

The default generated hashCode and equals implementations are ugly at best.

Is it possible to make eclipse generate ones from HashCodeBuilder and EqualsBuilder, and perhaps even a toString with ToStringBuilder?

+6  A: 

Take a look at Commons4E

It hasn't been updated in a while, but then I don't guess it needs to change much?

Update: Just checked against 3.4.1 and it works fine.

toolkit
+3  A: 

You can do that with Code Templates in Eclipse.

Here's a solution that I found with examples of HashCodeBuilder and EqualsBuilder.

Template EqualsBuilder:

    public boolean equals(Object o) {
        boolean result = false;

        if (this == o) {
            result = true;
        } else if (o instanceof $CLASSNAME$) {
            $CLASSNAME$ other = ($CLASSNAME$) o;

            result = new org.apache.commons.lang.builder.EqualsBuilder()
                    .append($END$
                    .isEquals();
        }

        return result;
    }

Template HashCodeBuilder:

    public int hashCode() {
        return new org.apache.commons.lang.builder.HashCodeBuilder()
                .append( $END$ )
                .toHashCode();
    }
bruno conde
Which code template is that for eclipse, or how do I make a new one?
daveb
Please see this post about code templates (existing and new ones): http://eclipse.dzone.com/news/visual-guide-templates-eclipse
bruno conde
Ande, your right about the existing primes ...
bruno conde
$CLASSNAME$ no longer works as of eclipse 3.4; the new variable is ${enclosing_type}. other $..$ should be replaces as well.
alex
Nice solution. Will it use all variables.
fastcodejava
+2  A: 

I use the Eclipse plugin called "Commonclipse"

After installation, you see a new context menu item "commonclipse" when you right click within a java source file. It can generate equals, hashcode, toString and compareTo methods based on the Apache commons libraries.

To install it, use this from within eclipse update: http://commonclipse.sourceforge.net

Chinnery
A: 

Eclipse java code templates for eclipse 3.5.0, derived from Bruno Conde's templates:

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    } else if (obj == this) {
        return true;
    } else if (obj.getClass() != this.getClass()) {
        return false;
    }

    ${enclosing_type} other = (${enclosing_type}) obj;
    return new EqualsBuilder()//
            .appendSuper(super.equals(other))//
            .append(${cursor})//
                .isEquals();
}

and

@Override
public int hashCode() {
    return new HashCodeBuilder(${cursor})//
            .append()//
            .toHashCode();
}
Jens Geiregat