我在几个类中的某些方法的顶部粘贴了一个注释@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 做得更“优雅”?
我不知道有什么捷径可以简化 Java 的反射 API。但您始终可以从 Groovy 的简洁性中受益:
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"]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)