Paulo Lopes
Paulo Lopes

Reputation: 5801

how to access groovy closure annotations?

Say that in my groovy code i've declared an closure with some annotation like this:

@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:

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)

Upvotes: 2

Views: 951

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27200

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.

Upvotes: 2

Related Questions