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脚本 . 这里有很多问题:如果在几个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()
本文介绍了一种使用Groovy进行脚本间方法导入及调用的方法。第一部分展示了通过import static语句直接引入Lib1.groovy文件中的静态方法f3和f4,并在Conf.groovy中调用这些方法。第二部分则探讨了通过GroovyShell解析Lib脚本,获取方法并转换为MethodClosure对象,最终在Conf.groovy中执行。
6593

被折叠的 条评论
为什么被折叠?



