Groovy / grails how to determine a data type?

GroovyTypes

Groovy Problem Overview


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.

Groovy Solutions


Solution 1 - Groovy

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)

Solution 2 - Groovy

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

Solution 3 - Groovy

Just to add another option to Dónal's answer, you can also still use the good old java.lang.Object.getClass() method.

Solution 4 - Groovy

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

assert Date.isCase(new Date())

Solution 5 - Groovy

somObject instanceof Date

should be

somObject instanceOf Date

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJack BeNimbleView Question on Stackoverflow
Solution 1 - GroovyDónalView Answer on Stackoverflow
Solution 2 - GroovyMichal Z m u d aView Answer on Stackoverflow
Solution 3 - GroovyPopsView Answer on Stackoverflow
Solution 4 - GroovyIbrahim.HView Answer on Stackoverflow
Solution 5 - GroovyMike NView Answer on Stackoverflow