Loading...

December 14, 2009

Groovy Goodness: Add Static Methods with MetaClass to Classes

Groovy's dynamic nature makes it easy to extend classes with new behaviour. One of the ways is to add methods or property to the metaClass property of a class. We can use the same mechanism to add static methods to the class. We only have to specify the keyword 'static' when we define the new method.

class User {
    String username, email
    String toString() { "$username, $email" }
}

User.metaClass.static.new = { u, e ->
    new User(username: u, email: e)
}

def u = User.new('mrhaki', 'mail@host.com')
assert 'mrhaki' == u.username
assert 'mail@host.com' == u.email
​