groovy - 为什么 groovy .class 返回与 .getClass() 不同的值

标签 groovy

根据http://groovy.codehaus.org/Things+you+can+do+but+better+leave+undone

  1. 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/

相关文章:

docker - Jenkins 管道 : docker. withServer(...) 不在远程服务器上执行 docker 命令

javascript - ${__RandomString(10,195165984,)} 放在 Jmeter 外部的脚本文件中然后调用它时不起作用

grails - 如何从我的服务中获取状态?

groovy - 在 Linux 上将 POI 添加到 groovy/java

java - 在 Elasticsearch 中查询以返回给定短语的所有结果

html - 从 CSS 链接的强大图像 URL?

xml - 使用 groovy 从上到下遍历 xml 文件

groovy - "Use"在 groovy 中如何工作?

Groovy 子类调用访问闭包的父类(super class)方法

testing - 无法将值传递给测试用例中的输入字段