在使用GroovyShell
执行脚本之前,需要访问groovy脚本文件中定义的变量
但是,我收到错误:
groovy.lang.MissingPropertyException: No such property: _THREADS for class: Test1
//Test1.groovy
_THREADS=10;
println("Hello from the script test ")
//scriptRunner.groovy
File scriptFile = new File("Test1.groovy");
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (scriptFile);
def thread = script.getProperty('_THREADS'); // getting ERROR --
// No such property: _THREADS for class: Test1
//-------
//now run the threads
script.run()
在获取属性/绑定之前必须运行脚本
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (''' _THREADS=10 ''')
script.run()
println script.getProperty('_THREADS')
尝试在groovy控制台中为以下代码打开AST Browser (Ctrl+T)
:
_THREADS=10
您将看到大约以下生成的类:
public class script1663101205410 extends groovy.lang.Script {
public java.lang.Object run() {
_THREADS = 10
}
}
其中_THREADS = 10
将属性分配给绑定
然而,可以将_THREADS定义为一个函数,这样就可以在不运行脚本的情况下访问它。
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (''' def get_THREADS(){ 11 } ''')
println script.getProperty('_THREADS')
使用@Field
获得解决方案,解析后可以访问修饰符值
import groovy.transform.Field
@Field _THREADS=10
File scriptFile = new File("Test1.groovy");
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (scriptFile);
def thread = script.getProperty('_THREADS'); //value is accessible