我使用groovy脚本中的方法创建了一个定制的dsl命令链。我在从另一个groovy文件访问这个命令链时遇到了问题。有什么方法可以实现这个功能吗?
我试过使用“计算”来加载groovy文件,但是它无法执行命令链。我尝试过使用Groovy类,但是无法调用这些方法。
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“的groovy文件。是否有一种方法可以在Main.groovy中直接执行上述命令链,如“请显示1000的cube_root”并获得所需的输出?
Main.groovy
please show the cube_root of 1000发布于 2019-04-05 19:12:58
在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
https://stackoverflow.com/questions/55540716
复制相似问题