Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy / grails how to determine a data type?

Tags:

types

groovy

People also ask

How do I know the datatype of a variable in Groovy?

You can use the getClass() method to determine the class of an object. Also, if you want to check if an object implements an Interface or Class, you can use the instanceof keyword. That's it about checking the datatype of an object in Groovy.

What is def in Groovy script?

The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.

How do I print values in a Groovy script?

You can use the print function to print a string to the screen. You can include \n to embed a newline character. There is no need for semi-colon ; at the end of the statement. Alternatively you can use the println function that will automatically append a newline to the end of the output.


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)

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.


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