1

I'm working for the first time with Groovy. I have a simple script, that I want to run on my Java server.

I build the script here MyScript in the Groovy web console, and when I run it, it returns what I expect [1,10].

minValue=1;
maxValue=10;
listValues=[];
enumMap=[];
rangeType="RANGE"; //RANGE,LIST,ENUM,NONE


Object test(int arg){
    return getRange();
}


Object[] getRange(){
    if (rangeType=="NONE"){
        return [];
    }

    if (rangeType=="RANGE"){
        return [minValue,maxValue];
    }

    if (rangeType=="LIST"){
        return listValues;
    }

    if (rangeType=="ENUM"){
        return enumMap;
    }
}

println(test(1));

On my Java server I invoke the test method this way

Script groovyScript = new GroovyShell().parse(script);
return groovyScript.invokeMethod("test", valueSuccess);

Although the script runs fine in the web console, when I run it on my server it gives me the following exception:

groovy.lang.MissingPropertyException: No such property: rangeType for class: Script1

The exact same script once runs without a problem, once it throws an exception. How can that be? It's not even complex, and the variable declarations should be correct, aren't they?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Herr Derb
  • 4,977
  • 5
  • 34
  • 62

1 Answers1

1

I would like you to import the field annotation package and correct the decalartion of variables.Specify some datatype for them along with the @Field annotation to access the variable anywhere in the script.

import groovy.transform.Field

@Field int minValue   = 1;
@Field int maxValue   = 10;
@Field List listValues= [];
@Field Map enumMap    = [:];
@Field def rangeType  = "RANGE"; //RANGE,LIST,ENUM,NONE

reference link for creating and accessing the global variables in Groovy

Community
  • 1
  • 1
Abhinandan Satpute
  • 2,558
  • 6
  • 25
  • 43
  • 1
    If he does that, it will not work anywhere. By defining them as he does, they are global variables within the script. Thus they are visible by the `getRange()` method. If he were to do as you ask, then none of these would be visible within the method and the script would fail. – BalRog Sep 27 '16 at 16:45
  • 1
    @BalRog.Good find.I have found a workaround for the same and added to the answer. – Abhinandan Satpute Sep 27 '16 at 17:02
  • 1
    @AbhinandanSatpute Thanks, that did the trick! there are just to many ways to define a variable in groovy... – Herr Derb Sep 28 '16 at 06:45