26

Is it possible to change the code generation template for equals() and hashCode()?

I would like the generated code to use the Java 7 Objects class for theses methods.

Rylander
  • 19,449
  • 25
  • 93
  • 144

4 Answers4

27

As of release 14.1 of the Ultimate Edition it is possible to customize the Code generation template of equals()/hashCode() without the use of any third party plugin.

Press "Alt + Insert" (Generate...), choose "equals() and hashCode()" and you will be able to select one of the predefined templates or a customized template of your own.

"Generate equals() and hashCode()" dialog

Edit "equals() and hashCode()" Velocity templates

datentyp
  • 1,371
  • 12
  • 9
  • Nice. Do you know where I can find a velocity template for generating equals and hashcode Eclipse style? – Timo Oct 27 '17 at 19:05
  • 1
    The trouble with this example is that it's the #addClassInstance macro that I'm not happy with, and it's used by all the templates. It gives me "if (o == null || getClass() != o.getClass()) return false;" but I want it to give me "if (!(o instanceof MyClass)) return false;". Does anyone know how to edit this macro? (I tried removing it, but I need a macro for the class name, and I don't know what it is.) – MiguelMunoz Jan 07 '20 at 22:24
5

UPDATE: have a look at the answer from @datentyp. Leaving mine for those stuck on the old versions

There are plugins to allow this. Please have a look at this ones:

http://plugins.jetbrains.com/plugin/6875?pr=idea

http://plugins.jetbrains.com/plugin/7244?pr=idea

They are opensource so you can amend them if you need to.

Community
  • 1
  • 1
klor
  • 3,596
  • 2
  • 13
  • 13
2

Update: As of version 14.1 this is supported.

Apparently this functionality does not exist.

There is a request for it though, see: http://youtrack.jetbrains.com/issue/IDEA-56007

Rylander
  • 19,449
  • 25
  • 93
  • 144
2

Yes it is possible, but with some small hack. Locate your idea.jar file in app folder. Look inside and find files like:

  • apacheEqualsBuilder3.vm
  • apacheHashCodeBuilder3.vm

and other .vm files..

These template files reuse some macros from equalsHelper.vm.

Change these files inside JAR carefully as you like restart app and check result in Idea under

generate->equals() and hashCode()->Template (... three dots on the right)->read only preview on the right side.

I think installing update of Idea may overwrite this JAR with your custom template changes.

It works! Checked in Idea 15. Enjoy. :-)

bigboban
  • 21
  • 1
  • I use this method in combination with previous to fine tune my generator templates for equals() and hashCode(). The code in "*.vm" files is written on Apache Velocity(http://velocity.apache.org) template language. – Rib47 Nov 22 '16 at 11:21