Sunday, 9 June 2013

IntelliJ IDEA Plugin - Guava based Generator for equals, hashCode andtoString

At my current role we've agreed on upon a team wide way to implement equals, hashCode and toString using some of the Guava utility libraries.

Pressing Alt+Ins (or Ctrl+N on the Mac) will bring up the Generate sub-menu (in the Java context only):

For a class with the following fields:

    private int field1, field2;
    private String field3, field4;

selecting Guava equals() and hashCode()... will generate the following code:

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TestClass that = (TestClass) o;

        return Objects.equal(this.field1, that.field1) &&
                Objects.equal(this.field2, that.field2) &&
                Objects.equal(this.field3, that.field3) &&
                Objects.equal(this.field4, that.field4);

    public int hashCode() {
        return Objects.hashCode(field1, field2, field3, field4);

and selecting Guava toString()... will generate the following code:

    public String toString() {
        return Objects.toStringHelper(this)

In both cases you'll be prompted to select the fields you wish to include in the generated methods.  Each time you use these generators the current implementations of equals & hashCode or toString (depending on your choice) will be replaced, if they exist.

The plugin can be found in the official Jetbrains IntelliJ plugin repository under "Guava equals, hashCode and toString generator".

The source code is available on GitHub

1 comment:

  1. It would be nice to have an optional ability to include field names in toString(), in addition to field values.