1

GroovyShell通过(解释器)运行以下 Groovy 表达式:

if(fizz.subtype == null) {
    if(fizz.color == 'RED') fizz.subtype = "DOG";
    else if(fizz.color == 'BLUE') fizz.subtype = "CAT";
    else if(fizz.color == 'GREEN') fizz.subtype = "SHEEP";
    else if(fizz.color == 'ORANGE') fizz.subtype = "LION";
    else if(fizz.color == 'YELLOW') fizz.subtype = "SNAIL";
    else if(fizz.color == 'GRAY') fizz.subtype = "SHARK";
    else if(fizz.color == 'PURPLE') fizz.subtype = "BAT";
    else if(fizz.color == 'BLACK') fizz.subtype = "FOX";
}; fizz;

给我以下堆栈跟踪:

groovy.lang.MissingPropertyException: No such property: subtype for class: com.me.myapp.Fizz
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:479)
    at Script1.run(Script1.groovy:1)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:543)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:518)
    at com.tms.evaluator.GroovyEvaluator._evaluate(GroovyEvaluator.java:51)
    ...rest of stacktrace omitted for brevity

有任何想法吗?提前致谢!

4

1 回答 1

1

您在if表达式的右括号后缺少一个分号:

fizz = [:]
if(fizz.subtype == null) {
    if(fizz.color == 'RED') fizz.subtype = "DOG";
    else if(fizz.color == 'BLUE') fizz.subtype = "CAT";
    else if(fizz.color == 'GREEN') fizz.subtype = "SHEEP";
    else if(fizz.color == 'ORANGE') fizz.subtype = "LION";
    else if(fizz.color == 'YELLOW') fizz.subtype = "SNAIL";
    else if(fizz.color == 'GRAY') fizz.subtype = "SHARK";
    else if(fizz.color == 'PURPLE') fizz.subtype = "BAT";
    else if(fizz.color == 'BLACK') fizz.subtype = "FOX";
}; fizz;

另外,我可以建议使用地图进行这种数据匹配吗?

fizz.color = 'ORANGE'

fizz.subtype = [
    'RED'    : 'DOG',
    'BLUE'   : "CAT",
    'GREEN'  : "SHEEP",
    'ORANGE' : "LION",
    'YELLOW' : "SNAIL",
    'GRAY'   : "SHARK",
    'PURPLE' : "BAT",
    'BLACK'  : "FOX"
][fizz.color]

assert fizz.subtype == 'LION'

案例匹配也可以工作,但如果您有更复杂的任务,它会最适合:

fizz.color = 'BLUE'

fizz.subtype = fizz.color.case {
    when 'RED'    then 'DOG'
    when 'BLUE'   then "CAT"
    when 'GREEN'  then "SHEEP"
    when 'ORANGE' then "LION"
    when 'YELLOW' then "SNAIL"
    when 'GRAY'   then "SHARK"
    when 'PURPLE' then "BAT"
    when 'BLACK'  then "FOX"
}

assert fizz.subtype == 'CAT'
于 2013-10-13T12:18:38.807 回答