Groovy / grails how to determine a data type?

Jack BeNimble picture Jack BeNimble · Jan 13, 2010 · Viewed 167.6k times · Source

What is the best way to determine the data type in groovy?

I'd like to format the output differently if it's a date, etc.

Answer

Dónal picture Dónal · Jan 13, 2010

To determine the class of an object simply call:

someObject.getClass()

You can abbreviate this to someObject.class in most cases. However, if you use this on a Map it will try to retrieve the value with key 'class'. Because of this, I always use getClass() even though it's a little longer.

If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:

(somObject instanceof Date)

or to check if the class of an object is exactly a particular class (not a subclass of it), use:

(somObject.getClass() == Date)