Including a groovy script in another groovy

前端 未结 12 1511
走了就别回头了
走了就别回头了 2020-11-27 12:07

I have read how to simply import a groovy file in another groovy script

I want to define common functions in one groovy file and call those functions from other groo

12条回答
  •  眼角桃花
    2020-11-27 12:31

    Groovy doesn't have an import keyword like typical scripting languages that will do a literal include of another file's contents (alluded to here: Does groovy provide an include mechanism?).
    Because of its object/class oriented nature, you have to "play games" to make things like this work. One possibility is to make all your utility functions static (since you said they don't use objects) and then perform a static import in the context of your executing shell. Then you can call these methods like "global functions".
    Another possibility would be using a Binding object (http://groovy.codehaus.org/api/groovy/lang/Binding.html) while creating your Shell and binding all the functions you want to the methods (the downside here would be having to enumerate all methods in the binding but you could perhaps use reflection). Yet another solution would be to override methodMissing(...) in the delegate object assigned to your shell which allows you to basically do dynamic dispatch using a map or whatever method you'd like.

    Several of these methods are demonstrated here: http://www.nextinstruction.com/blog/2012/01/08/creating-dsls-with-groovy/. Let me know if you want to see an example of a particular technique.

提交回复
热议问题