Platinum Solutions Corporate Website


Easy toString() Creation

Overriding the toString() method is an all too common Java developer experience. It’s also somewhat tedious: Write out the class name… write out some properties and their values… format it so it doesn’t look hideous… repeat for lots of other classes.

Wouldn't it be better if there were an automatic way to generate decent looking toString() methods?

Apache to the rescue!

Among the (extensive) collection of language utilities in Apache Commons is “commons lang”. In this package you can find the builder utilities which can make generating toString() methods a breeze.

Using it is simple enough. Just import the ToStringBuilder class, and write the toString method:

import org.apache.commons.lang.builder.ToStringBuilder;
...
public String toString() {
	return new ToStringBuilder(this).toString();
}

Tada! So, what does that return? Let’s take a look:

com.platinumsolutions.web.app.caseform.MyController@5e55ab[]

So... the full class name and the memory address? OK, that's a start, but let's change that to show the properties automatically:

public String toString() {
	return new ToStringBuilder(this).reflectionToString(this);
}

That returns:

com.platinumsolutions.web.app.caseform.MyController@81b1fb[anInt
=1234,someString=hello,myLong=123,formView=<null>,successView=,b
indOnNewForm=false,sessionForm=false,commandName=command,command
Class=<null>,validators=<null>,validateOnBinding=true,messageCod
esResolver=<null>,bindingErrorProcessor=<null>,propertyEditorReg
istrars=<null>,synchronizeOnSession=false,supportedMethods=[POST
, HEAD, GET],requireSession=false,useExpiresHeader=true,useCache
ControlHeader=true,cacheSeconds=0,servletContext=<null>,logger=o
rg.apache.commons.logging.impl.Log4JLogger@1cd107f,applicationCo
ntext=<null>,messageSourceAccessor=<null>]

Too much information! The reflectionToString() method might work on small classes, but for bigger ones, we probably want to pick and choose what variables to show:

public String toString() {
	return new ToStringBuilder(this).append("anInt", anInt)
		.append("myLong", myLong)
		.append("someString", someString).toString();
}

This results in:

com.platinumsolutions.web.app.caseform.MyController@6963d0[anInt
=1234,myLong=123,someString=hello]

Much better. Now let's try some different formatting:

public String toString() {
	return new ToStringBuilder(this,ToStringStyle.SHORT_PREFIX_STYLE)
		.append("anInt", anInt).append("myLong",myLong)
		.append("someString", someString).toString();
}

Now toString() returns:

MyController[anInt=1234,myLong=123,someString=hello]

Now there's a nice looking toString()!

Now, if they only had something for creating equals(), compareTo() and hashCode(). Oh wait, they do… and it’s in the same package.

Comments

Josh (not verified) Wed, 1969-12-31 19:00

If you used a higher level language like ruby you wouldn't have to worry about so much infrastructure. This kind of thing is much simpler and way less headache, not to mention less dependencies and lines of code.

You can pretty much do the same thing with the "inspect" method right out of the box. Nice and simple and powerful, not need for 3rd party libraries and builders.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options