![](/img/trans.png)
[英]Importing a groovy file from one package to another groovy file in another package
[英]how to include groovy dsl script from one groovy file to another
我已经使用groovy脚本中的方法创建了一个自定义dsl命令链。 我从另一个常规文件访问此命令链时遇到问题。 有没有办法实现功能?
我尝试使用“ evaluate”能够加载groovy文件,但无法执行命令链。 我尝试使用Groovy shell类,但是无法调用方法。
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
我还有一个名为“ Main.groovy”的常规文件。 有没有一种方法可以直接在Main.groovy中执行上述命令链,如“请显示1000的cube_root”并获得所需的输出?
Main.groovy
please show the cube_root of 1000
在groovy / java中没有include
操作
您可以使用GroovyShell
如果您可以将“ dsl”表示为闭包,那么这应该可以工作:
//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 ''')
另一种方法-使用类加载器
文件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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.