Saturday, December 22, 2012

Guava toString() method generator for IntelliJ IDEA

IntelliJ IDEA comes bundled with toString() plugin. If you check the plugins in Settings, you should find GenerateToString plugin, which generates toString() method with options for String concat, StringBuffer, StringBuilder and ToStringBuilder (of Apache Commons) for generating this method.

Google Guava has even better helper method for generating toString() method for a JavaBean or POJO, which is both clutter free and has a very consistent format; in the form of Objects.toStringHelper(this). It looks more elegant than any of the above solutions, actually. Also, as I make it a point to use Google Guava in all my projects, I have defined the following template in my toString() method generator settings in IntelliJ IDEA.

Follow the steps mentioned below for adding this template to your IntelliJ IDEA [picked up from SO]:
  • Go inside a Java Class in an editor in IntelliJ IDEA
  • Hit Alt + Insert to popup the "Generate" menu
  • Choose toString()
  • Click the "Settings" button
  • Go to the "Templates" tab
  • Create a new template named "Guava toString gen" (or any name you prefer)
  • Add the above code to the template
Yes, its that simple!!  After configuring the above template, whenever you want to generate a toString() method for a Class, IntelliJ IDEA generates toString() using Guava template you have added just now.

Now, go ahead and give this a try and also check the other method omitNullValues() which might be useful in some scenarios.


Also, as a bonus tip, Guava's Objects class also has 2 awesome helper methods which aide in writing readable equals() and hashcode() methods. You should try them too.


Update on 05th April, 2015: After a fair bit of time here, I have moved on to GitHub hosted Octopress blogs. Please find me on http://P7h.org henceforth for all new updates.