简体   繁体   English

Groovy 从应用程序访问脚本变量

[英]Groovy access script variable from application

Need to access the variable defined in the groovy script file需要访问groovy脚本文件中定义的变量
Before executing the script using GroovyShell在使用GroovyShell执行脚本之前
However, I am getting error:但是,我收到错误:

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

you have to run script before getting property/binding您必须在获取属性/绑定之前运行脚本

def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
def script = shell.parse (''' _THREADS=10 ''')
script.run()

println script.getProperty('_THREADS')

try to open AST Browser (Ctrl+T) in groovy console for this code:尝试在 groovy 控制台中打开AST Browser (Ctrl+T)以获取此代码:

_THREADS=10

and you'll see approximately following generated class:您将看到大约以下生成的 class:

public class script1663101205410 extends groovy.lang.Script { 
    public java.lang.Object run() {
        _THREADS = 10
    }
}

where _THREADS = 10 assigns property into binding其中_THREADS = 10将属性分配给绑定

however it's possible to define _THREADS as a function then it will be accessible without running script.但是,可以将 _THREADS 定义为 function,然后无需运行脚本即可访问它。

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

println script.getProperty('_THREADS')

got the solution using @Field modifier value can be accessed after parsing解析后可以访问使用@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM