If I have a List in a Grails domain class, is there a way to override the addX() and removeX() accessors to it?
In the following example, I'd expect MyObject.addThing(String) to be called twice. In fact, the output is:
Ad开发者_如何学JAVAding thing: thing 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 = {
}
}
The method should be called leftShift(String), not addThing(), as documented on the Groovy operator overloading page.
Moving my comment to an answer:
Try using the built-in addToThings as documented here:
http://www.grails.org/doc/latest/ref/Domain%20Classes/addTo.html
I don't understand why you expect addThing()
to be called twice? Here's an explanation of your code
// 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')
So you're only calling addThing()
once.
精彩评论