192

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.

noah
  • 21,289
  • 17
  • 64
  • 88
Jack BeNimble
  • 35,733
  • 41
  • 130
  • 213

5 Answers5

280

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)
Dónal
  • 185,044
  • 174
  • 569
  • 824
  • 2
    `instanceof` is great for filtering based on interface. – cdeszaq Mar 12 '13 at 13:15
  • At least in the latest Groovy (2.3.7), we can also write someObject.class – loloof64 Nov 07 '14 at 09:58
  • 5
    @LaurentBERNABE that works in most cases, but not in all, e.g. a `Map` instance – Dónal Nov 07 '14 at 12:51
  • You're right : we get null in this case. Apologizing for the mistake. – loloof64 Nov 07 '14 at 14:39
  • Then what is this? `def test = {} println test.getClass()` class Script1$_run_closure1 ?? – Petrunov May 24 '17 at 15:33
  • @Petrunov every closure is an anonymous subclass of `groovy.lang.Closure`. The name of the class is generated by the compiler, so`"Script1$_run_closure1"` is the name generated for your specific closure. This is pretty much the same for Java anonymous classes. – Dónal Jul 31 '19 at 00:28
35

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

Michal Zmuda
  • 5,381
  • 3
  • 43
  • 39
5

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

Dónal
  • 185,044
  • 174
  • 569
  • 824
Pops
  • 30,199
  • 37
  • 136
  • 151
1

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

assert Date.isCase(new Date())
Dónal
  • 185,044
  • 174
  • 569
  • 824
Ibrahim.H
  • 1,062
  • 1
  • 13
  • 22
-21

somObject instanceof Date

should be

somObject instanceOf Date

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
Mike N
  • 125
  • 1
  • 3