开发者

How to adding Dynamic Methods at Runtime to Grails domain object without creating plugins?

In the ref documentation I found only example such as

class ExamplePlugin {
  def doWithDynamicMethods = { applicationContext ->
        application.controllerClasses.each { controllerClass ->
             controllerClas开发者_Go百科s.metaClass.myNewMethod = {-> println "hello world" }
        }
  }
}

But I don't want to create plugin for such code...


You can add your dynamic methods in the grails-app/conf/BootStrap.groovy file in the init closure, then they should be available at app startup.

Note that the dynamic methods you add this way won't be available in your unit tests. They will be available in integration tests and at run-time.


you dont have to. Just the innermost line of your example is necessary. Assume you have

SomeDomain

as a class. You can do

SomeDomain.metaClass.newMethod  = {-> // stuff }

now I am going to go verify this...;)

Edit -- I've verified this. Just type the following into the groovy shell on the command line

class Example {}; Example.metaClass.newMethod = {-> println 'hello'}; def e = new Example(); e.newMethod()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜