我在Groovy Console中测试一些代码时遇到了一个奇怪的问题。以下代码:
class GameCharacter
{
def hp
def mp
def showInfo
}
c = new GameCharacter(hp: 0, mp: 0)
c.showInfo = {println "HP: ${hp} | MP: ${mp}"}
c.showInfo()
c.with{hp = 100 ; mp = 90}
c.showInfo()
给我以下输出:
HP: 100 | MP: 90
HP: 100 | MP: 90
为什么第一个p.showInfo()
调用没有显示第一个归零值?
答案 0 :(得分:1)
我真的很惊讶这段代码适合你。我在Groovy Console中得到了这个例外:
Exception thrown
Mar 30, 2011 2:40:47 PM org.codehaus.groovy.runtime.StackTraceUtils sanitize
WARNING: Sanitizing stacktrace:
groovy.lang.MissingPropertyException: No such property: hp for class: ConsoleScript0
所以我觉得showInfo应该打印你在GameCharacter中的字段。要修复你的代码,你可以a)在GameCharacter类中分配闭包:
class GameCharacter
{
def hp
def mp
def showInfo = {println "HP: ${hp} | MP: ${mp}"}
}
或b)如果您想稍后添加,可以通过元编程添加闭包:
class GameCharacter
{
def hp
def mp
}
c.metaClass.showInfo = {println "HP: ${hp} | MP: ${mp}"}
您将获得两种实施的正确结果:
HP: 0 | MP: 0
HP: 100 | MP: 90