Groovy调用另一个脚本来设置变量

时间:2019-04-18 18:19:40

标签: groovy groovyshell

我正在尝试在另一个要在当前脚本中使用的Groovy脚本中定义变量。我有两个这样的脚本:

script1.groovy

thing = evaluate(new File("script2.groovy"))
thing.setLocalEnv()
println(state)

script2.groovy

static def setLocalEnv(){
    def state = "hi"
    def item = "hey"
}

当我println(state)时,我得到了一个缺少的属性异常。基本上,我希望script2具有可以在script1上下文中加载的配置变量。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我不确定您到底想做什么/如何做,但是我想您可以使用groovy dynamique脚本功能中可用的类之一来实现您的目标:moviegroovy.lang.Binding或{ {1}},这是使用GroovyClassLoader类的示例:

GroovyScriptEngine

这是将变量绑定到外部脚本文件的一种方法,该文档提供了更多示例: http://docs.groovy-lang.org/latest/html/documentation/guide-integrating.html

P.S。可以使用GroovyShell完成加载外部文件:

abstract class MyScript extends Script {
    String name

    String greet() {
        "Hello, $name!"
    }
}

import org.codehaus.groovy.control.CompilerConfiguration

def config = new CompilerConfiguration()
config.scriptBaseClass = 'MyScript'
def shell = new GroovyShell(this.class.classLoader, new Binding(), config)
def script = shell.parse('greet()')
assert script instanceof MyScript
script.setName('covfefe')
assert script.run() == 'Hello, covfefe!'

希望这会有所帮助。

相关问题