This isn't exactly a solution to your question, but I no longer use the Eclipse auto-generated methods, I use the Apache commons lang EqualsBuilder and HashCodeBuilder:
So, for instance you can do:
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class EqualsTest {
private String foo;
private int bar;
// getters and setters
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}
This uses reflection, and doesn't need changing when you add a field. However, there are other options where you can specify the fields to use, and if you want to take into account the hashCode of the superclass as well.
EDIT: As has been pointed out, the reflection aspect of this may have some performance penalties associated. Personally, I don't use the reflection HashCodeBuilder or EqualsBuilder in production code, I use the toHashCode (as below). I do however use the ReflectionToStringBuilder for logging and such like.
Here is an example which doesn't use reflection, but requires you to add another line when you add a field:
public int hashCode() {
// you pick a hard-coded, randomly chosen, non-zero, odd number
// ideally different for each class
return new HashCodeBuilder(17, 37).
append(foo).
append(bar).
toHashCode();
}
For more discussion about hashCodeBuilder, see apache commons equals/hashcode builder