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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With