Francisco Francisco - 3 months ago 14
Groovy Question

No such property error for String in Groovy

So I have the following bit of code (the important bits):

import java.lang.String;
//More imports ...

String errorString = ""
//More global variables

def mainMethod(){
if (errorString.length()) {
errorString += "BTW, fields with errors must be either corrected or set back to their original value before proceeding."
invalidInputException = new InvalidInputException(errorString);
}
}


Then when I run the script Jira throws back at me in
catalina.out
the following error message:

groovy.lang.MissingPropertyException: No such property: errorString for class: com.onresolve.jira.groovy.canned.workflow.validators.editAssigneeValidation


So I am unsure on why the script is not recognizing errorString as a variable or not.

Answer

Because you are using this code as an script. Upon compilation, all code not contained in methods will be put in the run() method, thus, your errorString will be declared in the run() method, and your mainMethod() will try to work with an errorString which doesn't exist neither in its own scope nor in the class' scope.

Some solutions

1. @Field

Turns your errorString into a field in the compiled script class

@groovy.transform.Field String errorString = ""

def mainMethod(){
    if (errorString.length()) {
        errorString += "BTW, fields with errors must be either corrected or set back to their original value before proceeding."
        invalidInputException = [error: errorString]
    }
}

mainMethod()

2. Binding

Remove the type declaration, so errorString will be contained in the script's binding:

errorString = ""

def mainMethod(){
    if (errorString.length()) {
        errorString += "BTW, fields with errors must be either corrected or set back to their original value before proceeding."
        invalidInputException = [error: errorString]
    }
}

mainMethod()

Here is groovyConsole output of your script:

ast