gpt4 book ai didi

grails - 在 Controller 中覆盖 Getter

转载 作者:行者123 更新时间:2023-12-02 15:00:46 26 4
gpt4 key购买 nike

我似乎无法覆盖我的 grails Controller 中的 setter/getter 。下面提供了我为说明这一点而创建的示例代码:

class MyController extends RestfulController<MyDomainObj> {

def field
def getField(){
field += 1
}

def index(MyCommand command) {
field = 1
// in a controller this prints 1, but in my class it prints 2
println('field' + field)
}
}

如果我创建一个 Groovy 类并覆盖 getter,那么它就可以工作。
class X {

public static void main(String[] args){
def x = new X()
x.field = 1
println x.field
}

def field
def getField(){
field += 1
}
}

我在 Controller 中做错了什么还是 Controller 不支持此功能?如果不支持,那么有人知道为什么吗?发生了什么魔法会导致此功能不起作用?

最佳答案

对于类中的属性,Groovy 直接使用生成的私有(private)变量:

http://groovy.codehaus.org/Groovy+Beans :

If you access a property from within the class the property is defined in at compile time with implicit or explicit this (for example this.foo, or simply foo), Groovy will access the field directly instead of going though the getter and setter.



例子:
class C {

def prop

def getProp() {
println "getter"
prop
}

def dostuff() {
prop = "Y"
println prop
println getProp()
}

}

new C().dostuff()

结果是
Y
getter
Y

关于grails - 在 Controller 中覆盖 Getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23808827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com