I think I’m only five years behind the rest of the world, but I’ve recently had need to tinker with Commons BeanUtils and Commons Lang and have found some very nice stuff in there…

I’ve always wanted an easy and generic way to dump out the properties of an object in toString() but never had the passion to follow through… Groovy gives you the super-quick obj.dump() to see all the properties of an object… and I’ve often wished there was a simple way to do that in Java. Well enter the very useful ToStringBuilder and life gets very simple…

If you don’t mind coupling your domain classes to commons-lang, they just use it in your toString() method…

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

And if you do mind coupling, or it’s a third party object you want to dump out from some client code…

log.info("Current Org: [" +
    ToStringBuilder.reflectionToString(org)
    + "]");

Either way the output is quite tidy… and arrays are handled nicely… (I’ve reformatted to fit here, this is all on one line)

INFO: Current Org: [au.com.bytecode.dto.Org@652295fd[
    groups={Group1,Group2,Group3},
    address=PO Box 123,
    orgName=SampleOrg]]

Top stuff! You can even pass your own formatting objects if there’s a particular way you want ToStringBuilder to format your output. Nice.

Props to the Commons Lang boys.. I’m not sure I’ll need to write a custom toString() method ever again!