198

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.

5 Answers 5

287

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)
6
  • 2
    instanceof is great for filtering based on interface.
    – cdeszaq
    Commented Mar 12, 2013 at 13:15
  • At least in the latest Groovy (2.3.7), we can also write someObject.class
    – loloof64
    Commented Nov 7, 2014 at 9:58
  • 5
    @LaurentBERNABE that works in most cases, but not in all, e.g. a Map instance
    – Dónal
    Commented Nov 7, 2014 at 12:51
  • You're right : we get null in this case. Apologizing for the mistake.
    – loloof64
    Commented Nov 7, 2014 at 14:39
  • Then what is this? def test = {} println test.getClass() class Script1$_run_closure1 ??
    – Petrunov
    Commented May 24, 2017 at 15:33
35

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

0
5

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

1

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

assert Date.isCase(new Date())
-21

somObject instanceof Date

should be

somObject instanceOf Date

1
  • 15
    This is not correct. instanceof should all be in lower-case.
    – cdeszaq
    Commented Mar 12, 2013 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.