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?
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
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 (“””).
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.
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.
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!"
}
}
It is
if (other.getClass() == String)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With