首页 文章

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

提问于
浏览
1

我有一些库脚本:lib1.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脚本中?或者,有没有替代机制?我试图在跑步者脚本/ java类中运行conf.groovy(使用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)

1 回答

  • 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脚本 . 这里有很多问题:如果在几个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()
    

相关问题