Search

Dark theme | Light theme

January 18, 2010

Groovy Goodness: Override getProperty Method with Dynamic Groovy

Groovy's ExpandoMetaClass features allows us to override the getProperty() method for a class. This method is invoked if we want to access a property for an object. We can look up existing properties and return their result, but we can also write behaviour for the situation when the property doesn't exist.

class User {
    String username
}

User.metaClass.getProperty = { String propName ->
    def meta = User.metaClass.getMetaProperty(propName)
    if (meta) {
        meta.getProperty(delegate)
    } else {
        'Dynamic property for User'
    }
}

def mrhaki = new User(username: 'mrhaki')
def hubert = new User(username: 'hubert')

assert 'mrhaki' == mrhaki.username
assert 'Dynamic property for User' == mrhaki.fullname