2017-07-08 156 views
1

我有一些库脚本: lib1.groovy:包括Groovy脚本一些Groovy脚本

def a(){ 
} 

lib2.groovy:

def b(){ 
} 

lib3.groovy:

def c(){ 
} 

并希望在另一个脚本中使用它们: conf.groovy:

a() 
b() 
c() 

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

有什么办法可以将lib目录(脚本lib1,lib2m,lib3)中的所有脚本包含到conf.groovy脚本中? 或者,有没有其他的机制呢? 我想在runner脚本/ java类中运行conf.groovy(使用groovy shell,loader o脚本引擎)。

main.groovy:

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

的可能的复制[从groovy脚本加载脚本](https://stackoverflow.com/questions/9004303/load-script-from-groovy-script) –

+0

谢谢Szymon!但我不想在我的conf.groovy文件中插入def script = new GroovyScriptEngine('。').with {loadScriptByName('lib1.groovy')} this.metaClass.mixin脚本! conf.groovy是一个脚本,我给用户配置他的任务,我不希望用户参与此。其实我有另一个脚本(main.groovy)运行confg.groovy(使用GroovyShell,Loader或ScriptEngine)。我编辑的问题更清楚。 –

+0

你有c()在lib2和lib3中。哪一个应该被称为? – daggett

回答

1

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并将它们作为绑定传递给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()