我怎样才能覆盖“地图”? Grails 域类中的构造函数?
创建域类的新实例时,我需要执行一些初始化。
class ActivationToken {
String foo
String bar
}
当我这样做时,我希望 bar 由 ActivationToken 内的代码初始化:
def tok = new ActivationToken(foo:'a')
我看不到如何“覆盖”“构造函数”来实现这一点。我知道在这种情况下我可以添加一个普通的构造函数,但这只是一个简单的例子。
I need to perform some initialization when new instances of my domain class are created.
class ActivationToken {
String foo
String bar
}
When I do this I want bar to be initialized by code inside ActivationToken:
def tok = new ActivationToken(foo:'a')
I cannot see how to 'override' the 'constructor' to make this happen. I know in this case I could just add a normal constructor but this is just a simple example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
地图构造函数来自 Groovy - 在本例中不是 Grails。我做了一些实验,这就是我想到的:
基本上,如果您需要在构造后处理属性,则似乎必须手动重写构造函数。
或者,您可以覆盖各个设置器,这通常更干净、更安全:
请注意,默认值不会被处理,但在大多数情况下应该没问题。
The map constructor is coming from Groovy - not Grails in this case. I did some experimentation, and this is what I came up with:
Basically, it appears that you'll have to manually override the constructors if you need to process the property after construction.
Alternately, you can override individual setters, which is cleaner and safer in general:
Note that the default value isn't processed, but that should be OK in most instances.
上述解决方案也适用于从 Web 请求中的参数初始化对象的情况,例如,您希望忽略无关值、捕获 Missing property 异常。
The solution above is also good for cases where initializing an object from parameters in a web request, for example, where you wish to ignore extraneous values, catching Missing property exceptions.