Creating simple 'toString()' methods for Plain Old Groovy Beans (POGO's)

by 12/07/2007 02:26:00 PM 2 comments

Creating simple 'toString()' methods for Plain Old Groovy Beans (POGO's)

Hate to write toString() methods? Me too. I created a simple Category for generating formatted strings for my beans. This is nothing fancy but it illustrates how simple it is. First, I created a Category for dynamically adding methods to my classes.
package hohonuuli

class PropertyCategory {
    
    /**
     * List the property names of an object excluding class and metaClass
     */
    static List listKeys(Object self) {
        List keys = []
        self.properties.each {
            if (it.key != "metaClass" && it.key != "class") {
                keys << it.key
            }
        }
        return keys
    }  
    
    static String toXML(Object self) {
        def stringBuilder = new StringBuilder()
        stringBuilder.append("<${self.getClass().name}>")
        use (PropertyCategory) {
            List keys = listKeys(self)
            keys.sort().each { key ->
                stringBuilder.append("<${key}>").append(self."${key}".toString()).append("</${key}>")
            }
        }
        stringBuilder.append("</${self.getClass().name}>")
    }
    
}
Next, I create a bean and use the Cateogry in the toString method. In this case, I'm just dumping everything out as an XML fragment.
import hohonuuli.PropertyCategory

class AncillaryDatum 

    Date date
    def block
    def mode
    def type
    def depthMeters
    def temperatureCelsius
    def salinity

 
    String toString() {
        def s = ""
        // Here's the magic
        use (PropertyCategory) {
            s = this.toXML()
        }
        return s
    }
}
The output looks like:

<AncillaryDatum><block>2</block><date>Tue Jun 29 21:40:23 UTC</date><depthMeters>0.0050</depthMeters><mode>1</mode><salinity>0.0097</salinity><temperatureCelsius>19.1766</temperatureCelsius><type>18</type></AncillaryDatum>

You can format the output however you like and control what properties are written out. For example, you might want to ignore transient and static fields in you output. Enjoy

Brian Schlining

Developer

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

2 comments:

Guy Moller said...

in Ruby one would use the include statement in order to mixin the functionality of your PropertyCategory. is there a similiar thing in Groovy or do you have to use the use key word?

Hohonuuli said...

You can dynamically add methods to groovy classes using the metaClass...which isn't quite the same thing as a mixin. It's more like Ruby's open classes. There are a few hacks to do mixin style things in Groovy, and a proposal to add mixins to Groovy but for now use may be the closest thing.