Groovy:如何调用带注释的方法 [英] Groovy: How to call annotated methods
问题描述
在几个此类的某些方法的顶部,我有一个注释@MyAnnotation:
I have an annotation @MyAnnotation sticked on the top of some methods in a couple of classes like these:
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注释和相同方法参数(而不关心方法名称自身)的方法都将在运行时基于实例参数从网关"中调用.
Now I am expecting that every method annotated with @MyAnnotation and same method's arguments (not caring of the method's name self) it is called at runtime from the "gateway" based on the instanced parameter.
// 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更优雅"地做到这一点?
If I am going to solve it with Java I will probably end up to use "reflection" API and mapping the method names somewhere with some strategy. Is there a way to do it more "elegantly" with Groovy?
推荐答案
我不知道任何简化Java反射API的捷径.但是您总是可以从Groovy的简洁中受益:
I'm not aware of any shortcut to ease Java's reflection API. But you can always benefit from Groovy's terseness:
import java.lang.reflection.*
import java.lang.annotation.*
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface A {}
class Annotated {
@A def a() { "a" }
@A def b() { "b" }
def c() { "c" }
}
ann = new Annotated()
methods = ann.class.methods.findAll { it.getAnnotation(A) }
assert methods.size() == 2
assert methods.collect { it.invoke(ann) } == ["a", "b"]
这篇关于Groovy:如何调用带注释的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!