groovygroovyshellgroovyscriptengine

Groovy access script variable from application


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

Solution

  • 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