toString Velocity Template

1 min read

[@586]
toString Velocity Template

I'm using the excellent GenereateToString plugin to automatically create toString() methods in IDEA.

I've modified the default Velocity template as follows:

/**
* Returns a string representation of the object.
*
* @return A string representation of the object.
*/
public final String toString() {
final StringBuffer sb = new StringBuffer(super.toString());
#set ($i = 0)
#foreach ($member in $members)
#if (!$member.modifierStatic)
#if ($i == 0)
sb.append("[ ##
#else
sb.append(", ##
#end
#if ($member.string)
$member.name.replaceFirst("_", "") -> '")##
#else
$member.name.replaceFirst("_", "") -> ")##
#end
#if ($member.primitiveArray)
.append($member.name == null ? "null" : "");
sb.append('{');
for (int i = 0; $member.name != null && i < $member.name .length; ++i)
sb.append(i == 0 ? "" : ", ").append($member.name[i]);
sb.append('}');
#elseif ($member.objectArray)
.append($member.name == null ? "null" : Arrays.asList($member.name).toString());
#elseif ($member.string)
.append($member.accessor).append('\'');
#else
.append($member.accessor);
#end
#set ($i = $i + 1)
#end
#end
#if ($members.size() == 0)
sb.append("{}");
#else
sb.append(" ]");
#end
return sb.toString();
}

Here's an example of the code it automatically generates:

public class Test
{
  private String _name;
  private int _port;
  private String _url;
  private String[] _validIPs;
  // …
  /**   * Returms a string representation of the object.   *   * @return A string representation of the object.   */   public final String toString()   {     final StringBuffer sb = new StringBuffer(super.toString());     sb.append("[ name -> '").append(_name).append('\'');     sb.append(", url -> '").append(_url).append('\'');     sb.append(", port -> ").append(_port);     sb.append(", validIPs -> ").append((_validIPs == null) ? "null" : Arrays.asList(_validIPs).toString());     sb.append(" ]");
    return sb.toString();   } }

Here's a sample of what it returns:

Test@126b249[ name -> 'Test', url -> 'http://www.test.com', port -> 80, validIPs -> [127.0.0.1, localhost] ]

Overall not that many modifications from the default template:

  • The default template uses name=value, I use name -> value which I find more legible.
  • The default template prepends the class name, I prepend the super's toString() representation.
  • I also remove the underscore in front of field names, once again for legibility.
  • Finally, I added some javadoc comments.