October 2, 2009

Groovy Goodness: Expando as Dynamic Bean

The Expando class in Groovy is sort of a dynamic bean. We can add properties and we can add closures as methods to an instance of the Expando class. This is useful if we don't want to create a new class for a simple bean.

def user = new Expando(username: 'mrhaki')
assert 'mrhaki' == user.username

// Add an extra property.
user.email = 'email@host.com'
assert 'email@host.com' == user.email

// Assign closure as method. The closure can
// take parameters.
user.printInfo = { writer ->
    writer << "Username: $username"
    writer << ", email: $email"

def sw = new StringWriter()
assert 'Username: mrhaki, email: email@host.com' == sw.toString()