7

In Groovy I use the map literal notation quite frequently in my code, and was curious as to what concrete implementation of Map it was.

After trying a few things, this script best illustrates my confusion:

def map = ["A":"B"]
println map // I assume this avoids any lazy evaluation of the map
println map instanceof HashMap // I tried some other impls too
println map.class

and receive this output:

[A:B]
true
null

This tells me that the map is apparently a HashMap, but the getClass method doesn't want to tell me that.

So my question is: why is getClass returning null, and is there a more appropriate way to get runtime class info from Groovy?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Kirie
  • 93
  • 6

1 Answers1

9

You need to use

map.getClass()

As otherwise it's looking for a key called class

Nearly a duplicate of Why does groovy .class return a different value than .getClass()

Community
  • 1
  • 1
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Bah, I forgot Groovy could also interpret that as a map key. Thanks! – Kirie Nov 23 '15 at 20:37
  • 2
    #GroovyPuzzlers, S01. – JBaruch Nov 23 '15 at 20:48
  • 1
    I sometimes wonder why the community doesn't come together and shun scripting languages. This is the 30th "problem" I've had since I started learning Groovy, which I more or less have to if I want to get myself up to speed with Gradle. Everybody claims that scripting languages improve productivity. Is that a mockery of reality? While JavaScript moves towards being strongly typed and object oriented, JVM-based languages goes in the opposite direction. History repeats itself. – Martin Andersson Mar 17 '16 at 13:24