Groovy中的String没有此类属性错误

Fra*_*sco 2 groovy jira

因此,我有以下代码(重要部分):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,当我运行脚本时,Jira在catalina.out以下错误消息中向我抛出:

groovy.lang.MissingPropertyException: No such property: errorString for class: com.onresolve.jira.groovy.canned.workflow.validators.editAssigneeValidation
Run Code Online (Sandbox Code Playgroud)

因此,我不确定为什么脚本无法将errorString识别为变量。

Wil*_*ill 7

因为您正在使用此代码作为脚本。编译后,所有未包含在方法中的代码都将放入run()方法中,因此,errorString将在run()方法中声明您,并且您mainMethod()将尝试使用errorString既不在其自身范围内也不在类范围内的存在的an 。

一些解决方案:

1。 @Field

添加@Field将您errorString变成已编译脚本类中的字段

@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()
Run Code Online (Sandbox Code Playgroud)

2.绑定

删除类型声明,因此errorString将包含在脚本的绑定中:

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()
Run Code Online (Sandbox Code Playgroud)

这是脚本的groovyConsole输出:

AST