1

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()
Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22
Hexgear
  • 320
  • 1
  • 3
  • 13

2 Answers2

0

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')
daggett
  • 26,404
  • 3
  • 40
  • 56
  • Thanks, however, I need the user to define the values in the same script. read those values before executing the script – Hexgear Sep 14 '22 at 04:49
0

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
Hexgear
  • 320
  • 1
  • 3
  • 13