Intellij’s Java toString Update to Match Records

Intellij has code generation feature built into the IDE to allow Java developers to quickly generate boilerplate code including getters, setters, hashCode, equals and toString. The default implementation for the toString has always used braces for the demarcation between the class name and the variables. However, the Java record uses brackets for it’s default toString implementation. With no adjustments, you will end up with both implementations resulting in incongruent logging statements.

To achieve this, you can create a new template in Intellij that switches the brackets for the braces. Open up the generate dialog for the toString and click on the Settings button.

In the Templates tab, click on the String concat (+) template, and then click on the Copy button. You have to create a totally new template because they won’t let you edit the existing one. Name the new template String concat (+) brackets.

To switch out the braces for a brackets requires a bit of Velocity magic as the open bracket has meaning in the velocity world. We will need to add some surrounding bits as anything within #[[ … ]]# is unparsed. Here’s the completed template.

public java.lang.String toString() {
#if ( $members.size() > 0 )
#set ( $i = 0 )
    return "$classname#[[[]]#" +
#foreach( $member in $members )
#if ( $i == 0 )
    "##
#else
    ", ##
#end
#if ( $member.objectArray )
#if ($java_version < 5)
$member.name=" + ($member.accessor == null ? null : java.util.Arrays.asList($member.accessor)) +
#else
$member.name=" + java.util.Arrays.toString($member.accessor) +
#end
#elseif ( $member.primitiveArray && $java_version >= 5)
$member.name=" + java.util.Arrays.toString($member.accessor) +
#elseif ( $member.string )
$member.name='" + $member.accessor + '\'' +
#else
$member.name=" + $member.accessor +
#end
#set ( $i = $i + 1 )
#end
    ']';
#else
    return "$classname#[[[]]#]";
#end
}

Save it and then switch the template selection to use the new template. Once this is done, it will remain as the default and you’ll have consistent toString statements.

@Override
public String toString() {
    return "SystemEntity[" +
           "systemId=" + systemId +
           ", key='" + key + '\'' +
           ", lastName='" + lastName + '\'' +
           ']';
}

Leave a Reply

Your email address will not be published. Required fields are marked *