Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ Idea template for toString method using String.format instead of concatenation

I want to create IntelliJ Idea template for toString method using String.format instead of concatenation, StringBuffer, etc.

For example I have following object:

public class Foo {
    private int id;
    private String name;
    private List<String> values;
}

If I generate toString for all fields by default Idea will generate:

@Override
public String toString() {
    return "Foo{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", values=" + values +
            '}';
}

But I want to generate following:

@Override
public String toString() {
    return String.format("Foo(id=%d, name=%s, values=%s)", id, name, values);
}
like image 709
Yuriy Seredyuk Avatar asked Mar 11 '16 05:03

Yuriy Seredyuk


1 Answers

For anybody still looking for this:

public java.lang.String toString() {
return String.format(
"$classname (##
#set ($i = 0)
#foreach ($member in $members)
#if ($i != 0)##
, ##
#end
$member.name=%s##
#set ($i = $i + 1)
#end
)",##
#set ($i = 0)
#foreach ($member in $members)
    #if ($i != 0)
    ,##
    #end
    #if ($member.primitiveArray || $member.objectArray)
    java.util.Arrays.toString(this.$member.name)##
    #else
    this.$member.name ##
    #end
    #set ($i = $i + 1)
#end
);
}

Adapted from this template.

EDIT

For those who wonder what is this stuff (I wonder how you ended up here tbh, since the question is very specific xD): this is an IntelliJ template for generation of toString method.

Code generation helps you generate code constructs and recurring elements according to preset templates, instead of writing everything by hand.

Please read more here and here for toString specifically.

like image 102
Linuslabo Avatar answered Oct 02 '22 20:10

Linuslabo