Groovy access script variable from application

287 Views Asked by At

Need to access the variable defined in the groovy script file
Before executing the script using 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()
2

There are 2 best solutions below

0
Hexgear On BEST ANSWER

got the solution using @Field modifier value can be accessed after parsing

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
1
daggett On

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:

_THREADS=10

and you'll see approximately following generated class:

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

where _THREADS = 10 assigns property into binding

however it's possible to define _THREADS as a function then it will be accessible without running script.

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

println script.getProperty('_THREADS')