【问题标题】:In Groovy, how to get annotation values for parameters inside closures?在 Groovy 中,如何获取闭包内参数的注释值?
【发布时间】:2019-10-29 17:10:21
【问题描述】:

例如,给定这个 groovy 代码:

import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.ElementType
import java.lang.annotation.Target

@Target([ElementType.PARAMETER])
@Retention(RetentionPolicy.RUNTIME)
@interface Bar {
  String qux() default ""
}

def closure1 = { @Bar(qux = 'zxv') String foo ->
  println foo
}

println "[value for qux]"

如何打印 qux 的值(在本例中为 'zxv')?

【问题讨论】:

    标签: groovy


    【解决方案1】:

    Reflection API 可以为您提供所需的内容(我在 Java 8 上使用 Groovy 2.5)。

    闭包本质上是Closure 实例上名为call 的方法,parameterAnnotations[0][0] 是获取method 的第一个参数的第一个注释的快速方法。

    def anno = closure1.class.methods.find { it.name == 'call' }.parameterAnnotations[0][0]
    println anno.qux() // prints zxv
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多