0

我是 groovy 的新手。我试图弄清楚基本语法。以下代码片段:

def CRITICAL = 2;
def MAJOR = 3;
def MINOR = 9;
def GetPriorityFromString(String priorityStr) {
    switch (priorityStr){
        case "Critical" : return CRITICAL;
        case "Major" : return MAJOR;
        case "Minor" : return MINOR;
    }
    return 0;
}
GetPriorityFromString("Minor")

导致此错误:

groovy.lang.MissingPropertyException: No such property: MINOR for class: Script21

我做错了什么?

(而且由于我是这种语言的新手,请随意提出任何“groovier”方法来将字符串转换为枚举值。)

4

1 回答 1

1

只需使用地图

def mapping =["CRITICAL": 2, "MAJOR" : 3, "MINOR": 9]
println mapping["MINOR"]

至于您的原始代码:您的变量范围有问题。如果您在脚本上下文中,您可能不会使用“def”来声明全局变量,只需将其省略即可。

CRITICAL = 2;
MAJOR = 3;
MINOR = 9;
def GetPriorityFromString(String priorityStr) {
    switch (priorityStr){
        case "Critical" : return CRITICAL;
        case "Major" : return MAJOR;
        case "Minor" : return MINOR;
    }
    return 0;
}
GetPriorityFromString("Minor")

如果你把它放到一个普通的类中,那么你必须使用 defs

class Test {
def CRITICAL = 2;
def MAJOR = 3;
def MINOR = 9;
def GetPriorityFromString(String priorityStr) {
    switch (priorityStr){
        case "Critical" : return CRITICAL;
        case "Major" : return MAJOR;
        case "Minor" : return MINOR;
    }
    return 0;
}
}
new Test().GetPriorityFromString("Minor")
于 2013-03-27T18:23:59.927 回答