Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: check at run time if object is a String

Tags:

groovy

I'm about to overload the leftShift operator and wanted to know how to check if the given parameter "other" is a String?

def leftShift(other){
    if(other.getClass() instanceof String){
        println other.toString() + " is a string!"          
}

But this doesn't work.. Can anybody help me?

like image 788
user944351 Avatar asked Dec 14 '12 11:12

user944351


People also ask

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

Is string in Groovy?

Groovy Programming Fundamentals for Java DevelopersA String literal is constructed in Groovy by enclosing the string text in quotations. Groovy offers a variety of ways to denote a String literal. Strings in Groovy can be enclosed in single quotes ('), double quotes (“), or triple quotes (“””).

How do you check 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.

How do I use Instanceof in Groovy?

instanceof is a binary operator that we can use to check if an object is an instance of a given type. It returns true if the object is an instance of that particular type and false otherwise. Also, Groovy 3 adds the new ! instanceof operator.


2 Answers

You can use the test that you would normally use in Java.

def leftShift(other) {
    if(other instanceof String) {
        println "$other is a string!"
    }
}

When you call other.getClass() the result class is java.lang.Class instance which you could compare against String.class. Note other can be null in which the test "other instanceof String" evaluates to false.

UPDATE:

Here's a simple case that creates a Groovy GString instance which is not a string instance:

def x = "It is currently ${ new Date() }"
println x.getClass().getName()
println x instanceof String
println x instanceof CharSequence

Outputs:

It is currently Thu Aug 21 15:42:55 EDT 2014
org.codehaus.groovy.runtime.GStringImpl
false
true

GStringImpl extends GString which has methods that make it behave as a String object and implements CharSequence interface as does the String class. Check if other object is CharSequence which is true if object is a String or GString instance.

def leftShift(other) {
    if(other instanceof CharSequence) {
        println "$other is a string!"
    }
}
like image 110
CodeMonkey Avatar answered Oct 04 '22 08:10

CodeMonkey


It is

if (other.getClass() == String)
like image 20
user903772 Avatar answered Oct 04 '22 07:10

user903772