如何将groovy dsl脚本从一个groovy文件包含到另一个文件 [英] how to include groovy dsl script from one groovy file to another
问题描述
我已经使用groovy脚本中的方法创建了一个自定义dsl命令链.我从另一个groovy文件访问此命令链时遇到问题.有没有办法实现功能?
I have created a custom dsl command chain using methods in a groovy scripts . I have a problem in accessing this command chain from another groovy file . Is there a way to achieve the functionality ?
我尝试使用"evaluate"能够加载groovy文件,但是它无法执行命令链.我尝试使用Groovy shell类,但是无法调用方法.
I have tried using "evaluate" which is able to load the groovy file , but it is not able to execute the command chain. I have tried using Groovy shell class , but was not able to call the methods.
show = {
def cube_root= it
}
cube_root = { Math.cbrt(it) }
def please(action) {
[the: { what ->
[of: { n ->
def cube_root=action(what(n))
println cube_root;
}]
}]
}
please show the cube_root of 1000
在这里,我有一个CubeRoot.groovy,其中执行请显示1000的cube_root"结果为10
Here I have a CubeRoot.groovy in which executing "please show the cube_root of 1000" produces the result as 10
我还有一个名为"Main.groovy"的常规文件.有没有一种方法可以直接在Main.groovy中执行上述命令链,如请显示1000的cube_root"并获得所需的输出?
I have another groovy file called "Main.groovy" . Is there a way to execute the above command chain directly in Main.groovy as "please show the cube_root of 1000" and get the desired output ?
Main.groovy
Main.groovy
please show the cube_root of 1000
推荐答案
groovy/java中没有include
操作
there is no include
operation in groovy/java
,您可以使用 GroovyShell
如果您可以将"dsl"表示为闭包,那么这应该可以工作:
if you could represent your "dsl" as closures then for example this should work:
//assume you could load the lang definition and expression from files
def cfg = new ConfigSlurper().parse( '''
show = {
def cube_root= it
}
cube_root = { Math.cbrt(it) }
please = {action->
[the: { what ->
[of: { n ->
def cube_root=action(what(n))
println cube_root;
}]
}]
}
''' )
new GroovyShell(cfg as Binding).evaluate(''' please show the cube_root of 1000 ''')
另一种方法-使用类加载器
another way - use class loader
文件 Lang1.groovy
class Lang1{
static void init(Script s){
//let init script passed as parameter with variables
s.show = {
def cube_root= it
}
s.cube_root = { Math.cbrt(it) }
s.please = {action->
[the: { what ->
[of: { n ->
def cube_root=action(what(n))
println cube_root;
}]
}]
}
}
}
文件 Main.groovy
Lang1.init(this)
please show the cube_root of 1000
并从命令行运行:groovy Main.groovy
这篇关于如何将groovy dsl脚本从一个groovy文件包含到另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!