types check - Groovy / grails how to determine a data type?

if string (5)

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

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.

somObject instanceof Date

should be

somObject instanceOf Date

You can use the Membership Operator isCase() which is another groovy way:

assert Date.isCase(new Date())

To determine the class of an object simply call:


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)

You could add a method to String to make it more semantic:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

groovy:000> foo = ''
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true

groovy types