Friday, December 25, 2009

Groovy - dumping object's properties

Marry Christmas! This is the Christmas Eve and what follows is a Christmas Present for you!

Have you ever used BeanUtils from Apache to query the properties of an object? Was that easy? Well I did that and what I ended up was completely unreadable and chaotic. But there's good news! Here's how it's doable in Groovy:
object.properties
That's it! Groovy exposes the map of properties as a predefined property called "properties". Ain't that cool? Let's see how we would go about printing all the values of object's properties along with their names:
println object.properties.collect{it}.join('\n')
Here's what it's doing: it gets the map of properties, turns it into a list (collect{it}) and joins them with a new line character.

Did you notice that "class" is also one of the properties? That's nasty! How about filtering it out?
println object.properties.findAll{it.key != 'class'}.join('\n')
Now that's much better, but good only for one or two names to filter. How about a more general solution?
def filtered = ['class', 'active']
println object.properties
.collect{it}
.findAll{!filtered.contains(it.key)}
.join('\n')

That's much much better but still, if the object has like 15 properties looking them up is a pain if they are not sorted. Let's do something about it:
def filtered = ['class', 'active']

println object.properties
.sort{it.key}
.collect{it}
.findAll{!filtered.contains(it.key)}
.join('\n')

And there it is! A list of key=value (value taken from object's toString()) separated by a new-line character for easier browsing :)

I hope this will help you out with your Groovy adventures!

Have a nice holiday!

3 comments:

Anonymous said...

Cool, but Be aware of the object you want to get the properties. Some old java interfaces has some design bug with bad method name, so some getXXX is actually not read-only.

For example, if you call dataSource.properties, then you also call getConnection() which will consume a connection in the pool, and not gonna return it, making short of database pool.

Matthias Hryniszak said...

Thanks Kay, I didn't know that.

Unknown said...
This comment has been removed by the author.