在 Grails 中向对象添加方法并使其全局可用
我正在尝试利用 Groovy 的 metaclass
功能向 String 类添加一些字符串实用方法。现在,我的 BootStrap.groovy 脚本中的 init 闭包中有类似的内容:
String.metaClass.upper = {
delegate.toUpperCase()
}
问题是这个 upper
方法仅在 BootStrap 的范围内可用...尝试在其他地方使用它在 Grails 应用程序中不起作用,并且出现方法丢失错误。
有没有办法让这些方法随处可用?
I am attempting to add some string utility methods to the String class by utilizing Groovy's metaclass
functionality. Right now I have something like this in my init closure in my BootStrap.groovy script:
String.metaClass.upper = {
delegate.toUpperCase()
}
The problem is that this upper
method is only available within the scope of the BootStrap...trying to use it anywhere else in the Grails app does not work and I get method missing errors.
Is there any way to make those methods available everywhere?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在测试和运行环境中都会发生这种情况吗?有一个错误,每次单元测试后所有
metaClass
更改都会回滚: http://jira.grails.org/browse/GRAILS-8596Does this happen in both testing and running contexts? There is a bug where all
metaClass
changes get rolled back after each unit test: http://jira.grails.org/browse/GRAILS-8596