I used ToStringBuilder.reflectionToString(class)
in commons-lang, to implement toString()
for simple DTOs. Now I'm trying to use Google Guava instead of Apache commons library. And I found Objects.ToStringHelper
in Guava. But it's too verbose if there're lots of members in the class. For example:
@Override
public String toString() {
return MoreObjects.toStringHelper(this.getClass()).add("name", name)
.add("emailAddress", emailAddress)
.add("department", department).add("yearJoined", yearJoined)
.toString();
}
is much simpler if I use commons-lang:
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
Is there any better ways to implement toString()
with Guava, not with commons-lang?
I have a little trick for Guava's com.google.common.base.MoreObjects.toStringHelper()
. I configured IntelliJ IDEA to use it when auto-generating toString()
methods. I assume you can do the same in Eclipse. Here's how to do it in Intellij:
toString()
change the template to:
public String toString() {
#set ($autoImportPackages = "com.google.common.base.MoreObjects")
return MoreObjects.toStringHelper(this)
#foreach ($member in $members)
.add("$member.name", $member.accessor)
#end
.toString();
}
save the template, close the "Settings" and "Generate toString()" windows
Guava's MoreObjects.toStringHelper()
template when generating toString()
methodsWhen you add a new field to the class, simply re-generate the toString()
method (IDEA will ask you to confirm that you want to replace the existing toString()
method).