Given the 2 toString()
implementations below, which one is preferred:
public String toString(){
return \"{a:\"+ a + \", b:\" + b + \", c: \"
Apache Commons-Lang has a ToStringBuilder class which is super easy to use. It does a nice job of both handling the append-logic as well as formatting of how you want your toString to look.
public void toString() {
ToStringBuilder tsb = new ToStringBuilder(this);
tsb.append("a", a);
tsb.append("b", b)
return tsb.toString();
}
Will return output that looks like com.blah.YourClass@abc1321f[a=whatever, b=foo]
.
Or in a more condensed form using chaining:
public void toString() {
return new ToStringBuilder(this).append("a", a).append("b", b").toString();
}
Or if you want to use reflection to include every field of the class:
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
You can also customize the style of the ToString if you want.