Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No such property error for String in Groovy

Tags:

groovy

jira

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.

like image 289
Francisco Avatar asked Aug 31 '16 17:08

Francisco


1 Answers

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

Adding @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

like image 177
Will Avatar answered Sep 19 '22 11:09

Will