Groovy:如何调用带注释的方法

时间:2014-12-14 12:29:31

标签: java groovy

我有一个注释@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),它在运行时根据instanced参数从“网关”调用。

// 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更“优雅”地做到这一点?

1 个答案:

答案 0 :(得分:2)

我不知道任何简化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"]