17

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

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406

2 Answers2

23

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

tim_yates
  • 167,322
  • 27
  • 342
  • 338
9

A non-map example is the difference between the class of a type, and the class of an instance. The .class and .getClass() of an instance is its type, with some exceptions, e.g. maps. The .class of a type, is the type. The .getClass() of a type is java.lang.Class

For example:

def a = Integer.getClass()
def b = Integer.class
def c = 1.getClass()
def d = 1.class    

println a
println b
println c
println d

will give the output:

class java.lang.Class
class java.lang.Integer
class java.lang.Integer
class java.lang.Integer
kinbiko
  • 2,066
  • 1
  • 28
  • 40