简体   繁体   English

如何访问 groovy 闭包注释?

[英]how to access groovy closure annotations?

Say that in my groovy code i've declared an closure with some annotation like this:假设在我的 groovy 代码中,我已经声明了一个带有一些注释的闭包,如下所示:

@GET('/heartbeat')
def myClosure = { req, res ->
  res.end('OK')
}

so now in my code I would like to extract the GET annotation out of the closure so i could create some automatic mapping:所以现在在我的代码中,我想从闭包中提取GET注释,以便我可以创建一些自动映射:

public void doSomething(Closure closure) {
  closure.class.getAnnotations() // does not contain the GET annotation...
}

How can i get it?我怎么才能得到它?

So the full code would be:所以完整的代码是:

@GET('/heartbeat')
def myClosure = { req, res ->
  res.end('OK')
}

public void doSomething(Closure closure) {
  closure.class.getAnnotations() // does not contain the GET annotation...
}

doSomething(myClosure)

You can't.你不能。 The annotation is associated with the field, not the value of the field.注释与字段相关联,而不是字段的值。 The closure is the value of the field.闭包是该字段的值。 When you do something like closure.class.getAnnotations() you are asking for the annotations that are on the groovy.lang.Closure class, not the object which the “closure” variable there refers to.当您执行诸如closure.class.getAnnotations() 之类的操作时,您需要的是 groovy.lang.Closure 类上的注释,而不是那里的“closure”变量所指的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM