Groovy: check at runtime if an object is a string

I'm going to overload the leftShift statement and would like to know how to check if this parameter is a "different" string?

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

But that does not work. Can anybody help me?

+4
source share
3 answers

You can use the test that you usually use in Java.

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

When you call other.getClass() , the result class is an instance of java.lang.Class, which can be compared to String.class. Note another may be null, in which the test "other instanceof String" is false.

UPDATE:

Here is a simple example that creates an instance of Groovy GString that is not an instance of a string:

 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 like a String object and implements the CharSequence interface, like the String class. Check if the other CharSequence object is true if the object is an instance of String or GString.

 def leftShift(other) { if(other instanceof CharSequence) { println "$other is a string!" } } 
+9
source

it

 if (other.getClass() == String) 
+5
source

Written code will not compile - you are missing a parenthesis. At the same time, instanceof works the same way as in Java, as others mention. However, in Groovy, I would be careful with checking instanceof for String , because sometimes what Strings seems to be is actually GStrings (see docs , section “GStrings Are Not Strings”). Quick example:

 assert "the quick brown $somevar jumped over the lazy dog" instanceof String == false 
+1
source

All Articles