Using Google Guava's Objects.ToStringHelper

前端 未结 6 529
生来不讨喜
生来不讨喜 2021-01-30 10:36

I used ToStringBuilder.reflectionToString(class) in commons-lang, to implement toString() for simple DTOs. Now I\'m trying to use Google Guava instead

6条回答
  •  暖寄归人
    2021-01-30 11:00

    I have a little trick for Guava's com.google.common.base.MoreObjects.toStringHelper(). I configured IntelliJ IDEA to use it when auto-generating toString() methods. I assume you can do the same in Eclipse. Here's how to do it in Intellij:

    • go inside a class
    • 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's MoreObjects.toStringHelper()" (I did it by copying the "ToStringBuilder" template)
    • change the template to:

      public String toString() {
      #set ($autoImportPackages = "com.google.common.base.MoreObjects")
          return MoreObjects.toStringHelper(this)
      #foreach ($member in $members)
          .add("$member.name", $member.accessor)
      #end
          .toString();
      }
      
    • save the template, close the "Settings" and "Generate toString()" windows

    • you can now choose the Guava's MoreObjects.toStringHelper() template when generating toString() methods

    When you add a new field to the class, simply re-generate the toString() method (IDEA will ask you to confirm that you want to replace the existing toString() method).

提交回复
热议问题