简体   繁体   中英

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);
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM