Marslo
Marslo

Reputation: 3261

groovy: is there a way to get variable name

Assume:

Map map_a = [ 'x': 1 ]
Map map_b = [ 'y': 2 ]

I'd like to know whether if there's a way (i.e.: it.getVariableName or getVariableName(it)) in groovy as below:

[ map_a, map_b ].each {
  it.getVariableName       =>  'map_a' or 'map_b'
}

I suppose binding or metaClass might help, but don't know how to do it.

Upvotes: 0

Views: 307

Answers (2)

daggett
daggett

Reputation: 28634

the answer from Jeff is correct.

but keep in mind that you could do a lot of things with closures & maps in groovy that could give you nice syntax results

def maps=[:]
maps.with{
    map_a = [ 'x': 1 ]
    map_b = [ 'y': 2 ]
}

maps.each{k,v->
    println "$k :: $v"
}

result:

map_a :: [x:1]
map_b :: [y:2]

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27255

There is no way to do what you are talking about without introducing a compiler extension (AST transformation or similar). An object could have any number of references pointing to it and they could all have different names.

Upvotes: 2

Related Questions