No such property error for String in Groovy

时间:2016-08-31 17:57:01

标签: 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.

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:0)

You have to add @Field annotation to errorString:

import java.lang.String
import groovy.transform.Field
//More imports ...

@Field
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);
    }
}