为什么groovy.class返回的值不是.getClass() [英] Why does groovy .class return a different value than .getClass()

查看:264
本文介绍了为什么groovy.class返回的值不是.getClass()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



  1. 访问对象类型一个属性

使用.class而不是.getClass()就可以了 - 只要您知道
究竟是什么类型的你有的对象。但是,那么你不需要
。否则,你会冒险得到null或其他的东西,
但不是对象的类。



a = [:] println a.class .simpleName // NullPointerException,因为
.class是空的。


有人可以解释这是为什么吗?为什么 .class 返回与不同的东西getClass()

a 是一个映射时, a.class 是在Groovy中与 a.get(class)相同。正如你在文档中的例子中看到的,这将返回null。这就是为什么规则的趋势是要使用getClass,除非你确定变量不会是地图。


According to 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.

Can someone explain why this is? Why does .class return something different than getClass()

解决方案

Because when a is a map, a.class is the same in Groovy as a.get( "class" ). As you can see in the example in the docs, this will return null. That's why the rule trends to be to use getClass unless you're absolutely sure the variable won't be a map

这篇关于为什么groovy.class返回的值不是.getClass()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆