The title may be misleading. What I really want is to know the name of a closure within a controller. But closures in Groovy are always anonymous, so there is no name of the closure itself. But the closure is assigned to a variable, and I'm wondering if I can get the name of that variable. Perhaps an example will help. In a Grails controller imagine I have the following:
def get_data = {
Map results = [ 'errorCode' = -1, 'method' : 'get_data' ]
...
re开发者_如何学Gonder results as JSON
}
In the Map called results there's an element called 'method' that I want to assign to the name of this closure (or variable holding the closure to be more precise). Is this possible? The idea here is I want to generalize the results map and want to automatically populate an element called 'method'. Instinctively it feels like this should be possible but I haven't found any similar use cases that illustrate how. Any help much appreciated.
I don't think that you can get name of the variable in the general case. This is only a reference, and the closure can be assigned to many of them.
It is very simple, however, to get name of the current action in the controller code:
def get_data = {
def results = ['method': actionName]
}
See documentation.
精彩评论