是否可以覆盖Grails域类中的List访问器?

时间:2010-03-25 15:49:56

标签: java grails groovy dns

如果我在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 = {
    }
}

3 个答案:

答案 0 :(得分:2)

该方法应该被称为leftShift(String),而不是addThing(),如Groovy运算符重载page所述。

答案 1 :(得分:1)

将我的评论转到答案:

尝试使用此处记录的内置addToThings:

http://www.grails.org/doc/latest/ref/Domain%20Classes/addTo.html

答案 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()一次。

相关问题