【问题标题】:Groovy: How to call annotated methodsGroovy:如何调用带注释的方法
【发布时间】: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 个方法签名,然后将所有这些接口静态关联到同一个网关。

标签: java groovy


【解决方案1】:

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

【讨论】:

  • 感谢您的回答。仅使用标准的 java 反射,它看起来又好又干净。我会试一试的。
猜你喜欢
  • 1970-01-01
  • 2018-05-06
  • 2017-12-25
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2020-02-02
  • 1970-01-01
  • 2014-11-30
相关资源
最近更新 更多