Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

groovy

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()

like image 530
Jeff Storey Avatar asked Jul 16 '12 21:07

Jeff Storey


1 Answers

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

like image 147
tim_yates Avatar answered Oct 08 '22 14:10

tim_yates