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.propertiesThat'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']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:
println object.properties
.collect{it}
.findAll{!filtered.contains(it.key)}
.join('\n')
def filtered = ['class', 'active']And there it is! A list of key=value (value taken from object's toString()) separated by a new-line character for easier browsing :)
println object.properties
.sort{it.key}
.collect{it}
.findAll{!filtered.contains(it.key)}
.join('\n')
I hope this will help you out with your Groovy adventures!
Have a nice holiday!
3 comments:
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.
Thanks Kay, I didn't know that.
Post a Comment