使 Groovy 元类方法全局可用
我有一个 groovy 脚本 Bootstrap.groovy,其中我在 String 类上定义了几个元类方法。我的测试用例位于另一个文件 Test.groovy 中。在操作 String 时,如何使元类方法在 Test.groovy 中可用? (Iow,如何使元类方法在其他脚本/程序中全局可用)?
(我确实搜索并找到了一些相关问题,但他们没有具体回答这个问题。我使用的是Groovy 1.8.4)
I have a groovy script, Bootstrap.groovy, where I have defined several metaclass methods on the String class. I have my test cases in another file Test.groovy. How do I make the metaclass methods available in the Test.groovy, when manipulating String? (Iow, how do I make the metaclass methods globally available in other scripts/programs)?
(I did search and find some related questions, but they did not answer this specifically. Im using Groovy 1.8.4)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 DelegatingMetaClass 使这些对 String 类的添加全局可见。
Use the DelegatingMetaClass to make these additions to the String class globally visible.
我想我找到了一种方法来做到这一点:只需在
Test.groovy
中调用evaluate(new File("ch8/Bootstrap.groovy"))
即可。之前我尝试过 new GroovyShell().evaluate(),但这不是必需的。我可以直接调用evaluate()
方法。I think I found a way to do this: just call
evaluate(new File("ch8/Bootstrap.groovy"))
inTest.groovy
. Previously I was tryingnew GroovyShell().evaluate()
, but thats not required. I could directly call theevaluate()
method.