Groovy:map literal上的getClass方法返回null

Kir*_*rie 7 null groovy dictionary class

在Groovy中,我在代码中经常使用地图文字表示法,并对Map的具体实现感到好奇.

在尝试了一些事情之后,这个脚本最能说明我的困惑:

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
Run Code Online (Sandbox Code Playgroud)

并收到此输出:

[A:B]
true
null
Run Code Online (Sandbox Code Playgroud)

这告诉我地图显然是一个HashMap,但getClass方法不想告诉我.

所以我的问题是:为什么getClass返回null,是否有更合适的方法从Groovy获取运行时类信息?

tim*_*tes 9

你需要使用

map.getClass()
Run Code Online (Sandbox Code Playgroud)

否则它正在寻找一个叫做的密钥 class

几乎没有重复的为什么groovy .class返回一个不同于.getClass()的值

  • #GroovyPuzzlers,S01. (2认同)