Friday, September 16, 2005

Replicating Java’s Object.toString() method in CF

Here’s a little trick that may come in handy sooner or later. It’s something I desperately needed today, and was getting frustrated without it. In java if you call toString() on an object it returns the class name and the hex of its memory address. It’s quite handy for debugging things like making sure you're working with a singleton or a new object. But you can’t call toString() on a cfc. So here’s how you can get the same output in cf:

<cfset myObject = CreateObject('component','com.myco.MyObject') />
<cfset system = CreateObject('java','java.lang.System') />
<cfset objString = getMetaData(myObject).name & "@"& FormatBaseN(system.identityHashCode(myObject), 16) />

<cfdump var="#objString#" />

This will output something along the lines of 'com.myco.MyObject@fe029d42'. Just for a little teaser of what’s to come, I really wanted this for logging the creation of new cfcs with log4j. A little tutorial on using log4j with coldfusion is coming next…


Post a Comment

<< Home