Java 如何将groovy dsl脚本从一个groovy文件包含到另一个groovy文件
我使用groovy脚本中的方法创建了一个自定义dsl命令链。从另一个groovy文件访问此命令链时遇到问题。有没有实现功能的方法 我尝试过使用“evaluate”,它可以加载groovy文件,但无法执行命令链。我尝试过使用GroovyShell类,但无法调用这些方法Java 如何将groovy dsl脚本从一个groovy文件包含到另一个groovy文件,java,groovy,dsl,Java,Groovy,Dsl,我使用groovy脚本中的方法创建了一个自定义dsl命令链。从另一个groovy文件访问此命令链时遇到问题。有没有实现功能的方法 我尝试过使用“evaluate”,它可以加载groovy文件,但无法执行命令链。我尝试过使用GroovyShell类,但无法调用这些方法 show = { def cube_root= it } cube_root = { Math.cbrt(it) } def please(action) { [the: { what ->
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的多维数据集_根”将产生10的结果
我有另一个名为“Main.groovy”的groovy文件。是否有一种方法可以直接在Main.groovy中执行上述命令链,即“请显示1000的多维数据集_根”并获得所需的输出
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;
}]
}]
}
}
}
Lang1.init(this)
please show the cube_root of 1000
文件Main.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;
}]
}]
}
}
}
Lang1.init(this)
please show the cube_root of 1000
并从命令行运行:
groovymain.groovy
谢谢您的回答。是否有任何方法可以仅将脚本作为给定文件路径加载并绑定它,而不是在Main.groovy中加载完整脚本?def cfg=new ConfigSlurper().parse(new file(path_to_config).toURI().toul())
但是有很多变体。我想做的是,我在各种groovy文件中有各种groovy语句,类似于“please show the cube_root of 1000”。我想将所有这些groovy文件导入groovy,并使用这些语句构建一个新语句。有可能吗?我在答案中又加了一个例子