What's That Noise?! [Ian Kallen's Weblog]

« PHP versus J2EE | Main | What Is The Matrix? »

20040416 Friday April 16, 2004

Dumping Java object contents If you've ever exploited Perl's Data::Dumper to inspect a Perl object, you know how useful it can be. For Java programmers, the reflection API provides tools to perform a similar interogation but the API has long lacked a higher level tool. The Jakarta commons-lang jar has a goodie to help.

I first ran across the ToStringBuilder class looking for a tool to standardise the formatting of toString() -- it's annoying to trace a set of objects' contents to a log file and find that they all implement toString() with different levels of completeness or with different formatting conventions. Well, this class has another little gem in one of it's static methods. Check this out:
  System.out.println("An object: " + ToStringBuilder.reflectionToString(anObject));
      <Emeril Lagasse>BAM!</Emeril Lagasse>
That's it.

By providing a higher-level wrapper API, ToStringBuilder makes using reflection to dump a Java object contents a little bit easier. Of course, seeing as how I started off talking about Perl, it's worth a mention that TMTOWDI'ness presents itself in this case. The Java bean API's XMLEncoder can be used to serialize a Java object to XML. ( Apr 16 2004, 10:59:39 PM PDT ) Permalink
Comments [2]

Comments:

i can recommend xstream from codehaus for this. very easy to use and does what you expect.

Posted by morten wilken on April 19, 2004 at 07:37 PM PDT #

I've recently added a simple version of what tostringbuilder does, as a log4j 'filter'. You specify this filter on a log4j appender. As the appender processes events, if you pass a javabean to a logging method - logger.debug(mybean), the filter will tear through the javabean using reflection, setting a property on the logging event for each property found on the javabean. the object's 'tostring' method is used to build the logging message, unless you have a 'message' property on the bean. Properties are handy in logging events because you can specify them explicitly in pattern layouts. If you use a socketappender and the new version of Chainsaw (http://logging.apache.org/og4j/docs/chainsaw.html) - you can query for properties. For example, if you passed a javabean in to a logging method and the bean had a 'userid' field with a value of 'joe', in Chainsaw you could show all events which had joe as a userid by using this expression: prop.userid == 'joe' Chainsaw v2 is webstart-enabled - there's a link on the page to start it. There's also a tutorial on the Welcome tab. Hope you find it useful.

Posted by scott on September 06, 2004 at 11:09 AM PDT #

Post a Comment:

Comments are closed for this entry.