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

2 Answers 2

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, however, I need the user to define the values in the same script. read those values before executing the script
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.