5.8.2 Adding Dynamic Methods at Runtime - Reference Documentation
Authors: Andres Almiray
Version: 1.2.0
5.8.2 Adding Dynamic Methods at Runtime
For Griffon managed classes like controllers, models and so forth you can add methods, constructors etc. using the ExpandoMetaClass mechanism by accessing each controller's MetaClass:class ExampleAddon {
def addonPostInit(app) {
app.artifactManager.controllerClasses.each { controllerClass ->
controllerClass.metaClass.myNewMethod = {-> println "hello world" }
}
}
}
app.artifactManager
object to get a reference to all of the controller classes' MetaClass instances and then add a new method called myNewMethod
to each controller.
Alternatively, if you know before hand the class you wish add a method to you can simple reference that classes metaClass
property:class ExampleAddon { def addonPostInit(app) { String.metaClass.swapCase = {-> def sb = new StringBuffer() delegate.each { sb << (Character.isUpperCase(it as char) ? Character.toLowerCase(it as char) : Character.toUpperCase(it as char)) } sb.toString() } assert "UpAndDown" == "uPaNDdOWN".swapCase() } }
swapCase
to java.lang.String
directly by accessing its metaClass
.