gpt4 book ai didi

groovy - 在 groovy 脚本中包含一些 groovy 脚本

转载 作者:行者123 更新时间:2023-12-05 04:10:03 25 4
gpt4 key购买 nike

我有一些库脚本:lib1.groovy:

def a(){
}

lib2.groovy:

def b(){
}

lib3.groovy:

def c(){
}

并想在其他脚本中使用它们:配置文件:

a()
b()
c()

conf.groovy 是由用户配置的,他不知道我的后台库脚本!他只知道提供的方法/任务:a()、b()、c()。实际上,我为用户简单性创建了 lib 脚本。

有没有办法将 lib 目录中的所有脚本(脚本 lib1、lib2m、lib3)包含到 conf.groovy 脚本中?或者,是否有替代机制?我正在尝试在运行器脚本/java 类中运行 conf.groovy(使用 groovy shell、加载器或脚本引擎)。

main.groovy:

File currentDir = new File(".")
String[] roots = {currentDir.getAbsolutePath()}
GroovyScriptEngine gse = new GroovyScriptEngine(roots)
gse.run('confg.groovy', binding)

最佳答案

v1

使用import static和静态方法声明:

Lib1.groovy

static def f3(){
println 'f3'
}
static def f4(){
println 'f4'
}

Conf.groovy

import static Lib1.* /*Lib1 must be in classpath*/

f3()
f4()

v2

或另一个想法(但不确定您是否需要这种复杂性):使用 GroovyShell 解析所有 lib 脚本。从每个 lib 脚本类中获取所有非标准声明的方法,将它们转换为 MethodClosure 并将它们作为绑定(bind)传递到 conf.groovy 脚本中。这里有很多问题,例如:如果方法在多个库中声明怎么办...

import org.codehaus.groovy.runtime.MethodClosure
def shell = new GroovyShell()
def binding=[:]
//cycle here through all lib scripts and add methods into binding
def script = shell.parse( new File("/11/tmp/bbb/Lib1.groovy") )
binding << script.getClass().getDeclaredMethods().findAll{!it.name.matches('^\\$.*|main|run$')}.collectEntries{[it.name,new MethodClosure(script,it.name)]}

//run conf script
def confScript = shell.parse( new File("/11/tmp/bbb/Conf.groovy") )
confScript.setBinding(new Binding(binding))
confScript.run()

Lib1.groovy

def f3(){
println 'f3'
}
def f4(){
println 'f4'
}

Conf.groovy

f3()
f4()

关于groovy - 在 groovy 脚本中包含一些 groovy 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44983338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com