在 Grails 中向对象添加方法并使其全局可用

发布于 2025-01-03 00:03:51 字数 317 浏览 3 评论 0原文

我正在尝试利用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九歌凝 2025-01-10 00:03:51

在测试和运行环境中都会发生这种情况吗?有一个错误,每次单元测试后所有 metaClass 更改都会回滚: http://jira.grails.org/browse/GRAILS-8596

Does 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文