【发布时间】:2011-07-29 23:02:06
【问题描述】:
我有一个简单的 Groovy 类别类,它向 String 实例添加方法:
final class SampleCategory {
static String withBraces(String self) {
"($self)"
}
}
我想在我的单元测试中使用这个类别(例如)。它看起来像这样:
class MyTest {
@Test
void shouldDoThis() {
use (SampleCategory) {
assert 'this'.withBraces() == '(this)'
}
}
@Test
void shouldDoThat() {
use (SampleCategory) {
assert 'that'.withBraces() == '(that)'
}
}
}
然而,我想要实现的是能够指定 SampleCategory 类别在 MyTest 的每个实例方法的范围内使用,因此我不必在每个方法中指定 use(SampleCategory) { ... } .
有可能吗?
【问题讨论】:
-
应该可以使用 AST 转换,但不知道如何实现它。用户指南here 中有一个部分,Hamlet D'arcy 在他的"Code generation on the JVM"-talk 中谈到了它(不确定他有多深入)。祝你好运!
-
谢谢你的想法!听起来像是一个不错的小型 OSS 项目候选人 :)
标签: groovy metaprogramming categories metaclass