【发布时间】:2014-12-14 12:29:30
【问题描述】:
我有一个注释 @MyAnnotation 贴在几个类中的一些方法的顶部,例如:
FirstClass {
@MyAnnotation
doSomethingWith(String text) { println 'text from first class' }
@MyAnnotation
doSomethingWith(Foo foo) { println 'foo from first class' }
@MyAnnotation
doAlsoSomethingWith(Bar bar) { println 'bar from first class' }
}
SecondClass {
@MyAnnotation
doOtherStuffWith(Foo foo) { println 'foo from second class' }
}
GenericGateway {
execute(instancedParam) {
// call something passing an instance of "Foo" class
// call something passing an instance of "Bar" class
// call something passing an instance of "String" class
}
}
现在我期望每个使用 @MyAnnotation 注释的方法和相同方法的参数(不关心方法的名称 self)在运行时根据实例化参数从“网关”调用。
// Example:
gateway.execute(new Foo(...))
gateway.execute('something')
gateway.execute(new Bar(...))
// I am expecting to see:
foo from first class
foo from second class
text from first class
bar from first class
如果我要使用 Java 解决它,我可能最终会使用“反射”API 并使用某种策略将方法名称映射到某个地方。有没有办法用 Groovy 更“优雅”地做到这一点?
【问题讨论】:
-
你现在卡在哪里了?你谷歌了,为什么你有一个标签 groovy 和 java?
-
标签 groovy 是因为我试图仅使用“groovy”来解决它。 Groovy 为您提供了许多相对于 Java 的元编程替代方案,所以我想知道是否有一些东西可以更好地解决此类问题。
-
为什么在这种情况下要依赖注解而不是通用接口?
-
因为如果你创建 2000 个具有不同签名的方法,你必须在表达相同概念的不同接口上创建 2000 个方法签名,然后将所有这些接口静态关联到同一个网关。