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

在groovy脚本中包含一些groovy脚本,groovy,include,Groovy,Include,我有一些库脚本: lib1.groovy: def a(){ } lib2.groovy: def b(){ } lib3.groovy: def c(){ } 并希望在其他脚本中使用它们: conf.groovy: a() b() c() groovy是由用户配置的,他不知道我的后台lib脚本!他只知道提供的方法/任务:a(),b(),c()。实际上,我创建了lib脚本以简化用户 有没有办法将lib目录中的所有脚本(脚本lib1、lib2m、lib3)都包含到conf.groovy脚本

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

def a(){
}
lib2.groovy:

def b(){
}
lib3.groovy:

def c(){
}
并希望在其他脚本中使用它们: conf.groovy:

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

有没有办法将lib目录中的所有脚本(脚本lib1、lib2m、lib3)都包含到conf.groovy脚本中? 或者,有什么替代机制吗? 我试图在runner脚本/java类中运行conf.groovy(使用GroovyShell、loader o脚本引擎)

main.groovy:

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

使用导入静态和静态方法声明:

Lib1.groovy

static def f3(){
    println 'f3'
}
static def f4(){
    println 'f4'
}
def f3(){
    println 'f3'
}
def f4(){
    println 'f4'
}
Conf.groovy

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

f3()
f4()
f3()
f4()

v2

或者另一个想法(但不确定您是否需要这种复杂性):使用
GroovyShell
解析所有lib脚本。从每个lib脚本类获取所有非标准声明的方法,将它们转换为MethodClosure,并将它们作为绑定传递到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()
Conf.groovy

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

f3()
f4()
f3()
f4()

谢谢Szymon的可能副本!但我不想在conf.groovy文件中插入def script=new GroovyScriptEngine('.')。使用{loadScriptByName('lib1.groovy')}this.metaClass.mixin script!。groovy是我给用户的一个脚本,用于配置他的任务,我不希望用户参与其中。实际上,我有另一个脚本(main.groovy)运行confg.groovy(使用GroovyShell、Loader或ScriptEngine)。我对问题进行了编辑以使其更清楚。lib2和lib3中都有c()。应该叫哪一个?名称已更正!它是a()、b()和c()!