如果我在Grails域类中有一个List,是否有办法覆盖addX()和removeX()访问器?
在下面的示例中,我希望MyObject.addThing(String)被调用两次。实际上,输出是:
添加东西:东西2
class MyObject {
static hasMany = [things: String]
List things = []
void addThing(String newThing) {
println "Adding thing: ${newThing}"
things << newThing
}
}
class BootStrap {
def init = { servletContext ->
MyObject o = new MyObject().save()
o.things << 'thing 1'
o.addThing('thing 2')
}
def destroy = {
}
}
答案 0 :(得分:2)
该方法应该被称为leftShift(String),而不是addThing(),如Groovy运算符重载page所述。
答案 1 :(得分:1)
答案 2 :(得分:0)
我不明白为什么你期望addThing()
被召唤两次?这是对您的代码的解释
// things is a List, so this calls List.leftShift(Object)
o.things << 'thing 1'
// o is an instance of MyObject, so this calls addThing()
o.addThing('thing 2')
因此,您只需拨打addThing()
一次。