Quantcast
Channel: Jworks » intellij
Viewing all articles
Browse latest Browse all 5

Generate a toString using Guava Objects.toStringhelper with IntelliJ

$
0
0

In IntelliJ it’s possible to generate a toString using Alt+Insert (Windows) or Ctrl+N (Mac). In this dialog, you can choose to use different implementations, like a StringBuffer, a StringBuilder, Apache Commons ToStringBuilder, and more. But if you’re using Google Guava, you can create your own template in IntelliJ. To do so, do the following:

  • Open a class file
  • Press Alt + Insert or Ctrl + N to popup the ‘Generate’ menu
  • Choose toString()
  • Click the button named ‘Settings’
  • Go to the ‘Templates’ tab
  • Create a new template named
  • Add the following in the template:

public String toString() {
#set ($autoImportPackages = "com.google.common.base.Objects")
   return Objects.toStringHelper(this)
#foreach ($member in $members)
   .add("$member.name", $member.accessor)
#end
   .toString();
}

This template is based on the Apache Commons toStringBuilder, and will generate a consistent toString for you using Google Guava.

The post Generate a toString using Guava Objects.toStringhelper with IntelliJ appeared first on Jworks.


Viewing all articles
Browse latest Browse all 5