ExpandoMetaClass
Language/Groovy 2016. 9. 8. 15:54ExpandoMetaClass - 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"
'Language > Groovy' 카테고리의 다른 글
Metaprogramming (0) | 2016.09.09 |
---|---|
그루비의 동적 객체지향 - 1 (0) | 2016.09.09 |
그루비의 동적 객체지향 - 2 (0) | 2016.09.08 |
What does .delegate mean in groovy? (0) | 2016.09.08 |
Groovy - 문법 (Java 와 비교해서 다른 점 위주로) (0) | 2016.09.05 |