Groovy 中的字符串没有这样的 属性 错误

No such property error for String in Groovy

所以我有以下代码(重要的部分):

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

然后当我 运行 脚本 Jira 在 catalina.out 中向我反馈以下错误消息:

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

所以我不确定为什么脚本没有将 errorString 识别为变量。

您必须将 @Field 注释添加到 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);
    }
}

因为您将此代码用作脚本。编译时,所有不包含在方法中的代码都将放在 run() 方法中,因此,您的 errorString 将在 run() 方法中声明,而您的 mainMethod() 将尝试使用既不存在于它自己的范围内也不存在于 class' 范围内的 errorString

一些解决方案:

1。 @Field

添加 @Field 会将您的 errorString 变成已编译脚本中的一个字段 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。绑定

删除类型声明,因此 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()

这是您的脚本的 groovyConsole 输出: