通过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
有什么想法吗?提前谢谢!
答案 0 :(得分: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'
case-match也可以使用,但如果您的任务更复杂,那么它最适合:
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'