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" }
}
}
}
In this case we use the 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()
}
}
In this example we add a new method swapCase
to java.lang.String
directly by accessing its metaClass
.