根据http://groovy.codehaus.org/Things+you+can+do+but+better+leave+undone
- Accessing an object's type like a property
Using .class instead of .getClass() is ok - as long as you know exactly what kind of object you have. But then you don't need that at all. Otherwise, you run in the risk of getting null or something else, but not the class of the object.
a = [:] println a.class.simpleName // NullPointerException, because a.class is null.
有人能解释一下这是为什么吗?为什么 .class
返回的内容与 getClass()
最佳答案
因为当 a
是映射时,a.class
在 Groovy 中与 a.get( "class")
相同。正如您在文档中的示例中看到的,这将返回 null。这就是为什么规则倾向于使用 getClass ,除非您完全确定变量不会是映射
关于groovy - 为什么 groovy .class 返回与 .getClass() 不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11512978/