In order to create new macro for Java equals implementation in Eclipse follow these steps (I have Eclipse 3.4 but steps should be similar for older versions also):
- go to Preferences > "Java > Editor > Templates
- Choose "New..." and enter following values:
Name equals Description Default equals implementation Pattern public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ${enclosing_type})) { return false; } ${enclosing_type} other = (${enclosing_type}) obj; //TODO finish equals throw new UnsupportedOperationException("Equals for ${enclosing_type} is not implemented"); }
Comments (3)
Aug 07, 2008
Sven Filatov says:
If you usually have commons-lang library included in your projects, then this mi...If you usually have commons-lang library included in your projects, then this might be useful as well:
And similar templates for hashCode() and toString() using HashCodeBuilder and ToStringBuilder as well.
There's also trivial versions of the three methods possible:
But I wouldn't recommend this because usually there's at least one field you don't want to appear in equals() and hashCode(), and by specifying such field(s) you would lose refactoring support.
Aug 07, 2008
Sven Filatov says:
For completeness' sake, here's the template for hashCode(): public int hashCod...For completeness' sake, here's the template for hashCode():
And template for toString():
Oct 09, 2008
Anonymous says:
You can also add a template for an import statement of the respective *Build...You can also add a template for an import statement of the respective *Builder.
For instance:
${:import(org.apache.commons.lang.builder.EqualsBuilder)}which evaluates to nothing but adds an import statement if needed.