应用程序中的Groovy访问脚本变量

46scxncf  于 2022-09-21  发布在  其他
关注(0)|答案(2)|浏览(176)

需要访问在groovy脚本文件中定义的变量
在使用GroovyShell执行脚本之前
然而,我收到了错误:

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()
wr98u20j

wr98u20j1#

在获取属性/绑定之前,您必须运行脚本

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将属性分配给绑定

但是,也可以将_thresses定义为一个函数,然后无需运行脚本即可访问它。

def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (''' def get_THREADS(){ 11 } ''')

println script.getProperty('_THREADS')
agxfikkp

agxfikkp2#

得到了使用@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

相关问题