Reputation: 65
I have some library scripts: lib1.groovy:
def a(){
}
lib2.groovy:
def b(){
}
lib3.groovy:
def c(){
}
and want to use them in another scripts : conf.groovy:
a()
b()
c()
conf.groovy is configured by user and he is not aware of my background lib scripts! he is only aware of provided methods/task : a(), b(), c(). actually i created lib scripts for user simplicity.
Is there any way to include all scripts in a lib directory (scripts lib1, lib2m ,lib3) into conf.groovy script(s)? Or, is there any alternative mechanism to to that? I am trying to run conf.groovy in a runner script/java class (using groovy shell, loader o script engine).
main.groovy:
File currentDir = new File(".")
String[] roots = {currentDir.getAbsolutePath()}
GroovyScriptEngine gse = new GroovyScriptEngine(roots)
gse.run('confg.groovy', binding)
Upvotes: 4
Views: 4756
Reputation: 28564
v1
use import static
and static methods declaration:
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
or another idea (but not sure you need this complexity): use GroovyShell
to parse all lib scripts. from each lib script class get all non-standard declared methods, convert them into MethodClosure and pass them as binding into conf.groovy script. And a lot of questions here like: what to do if method declared in several Libs...
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()
Upvotes: 3