Dashboard > Groovy > ... > ExpandoMetaClass > ExpandoMetaClass - Interfaces
ExpandoMetaClass - Interfaces Log In | Sign Up   View a printable version of the current page.

Added by Graeme Rocher , last edited by Tom Nichols on Sep 05, 2007  (view change)
Labels: 
(None)

ExpandoMetaClass - Adding methods to interfaces

It is possible to add methods onto interfaces with ExpandoMetaClass. To do this however, it MUST be enabled globally using the ExpandoMetaClass.enableGlobally() method before application start-up.

As an example this code adds a new method to all implementors of java.util.List:

List.metaClass.sizeDoubled = {-> delegate.size() * 2 }

def list = []

list << 1
list << 2

assert 4 == list.sizeDoubled()

Another example taken from Grails, this code allows access to session attributes using Groovy's subscript operator to all implementors of the HttpSession interface:

HttpSession.metaClass.getAt = { String key ->
        delegate.getAttribute(key)
  }
  HttpSession.metaClass.putAt = { String key, Object val ->
        delegate.setAttribute(key, val)
  }  

  def session = new MockHttpSession()

  session.foo = "bar"
Site running on a free Atlassian Confluence Open Source Project License granted to The Codehaus. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.6.2 Build:#919 Nov 26, 2007) - Bug/feature request - Contact Administrators