Skarab
Skarab

Reputation: 7141

How to check if an instance is of type String or GString in Groovy

I would like to learn what the robust way of checking, if a variable is of type string or gstring, is. I suppose it is different than in pure Java:

def var = someFunc();

if (var instanceof String || var instanceof GString) {
   String str = var;
}

I ask, because I do not want to be surprised that I have missed a Groovy specific feature that causes a hard to debug bug.

Upvotes: 44

Views: 57285

Answers (4)

vtvitus
vtvitus

Reputation: 11

def var = someFunc();

if (var.toString() == var) {
   def str = var;
}

Upvotes: 0

Al Baker
Al Baker

Reputation: 534

You can also use the .class method on a Groovy object

def a = "test"
def b = "${a}"

assert a.class == String
assert b.class == org.codehaus.groovy.runtime.GStringImpl

Note that a GString is easily evaluated and turned into a String, e.g. by calls to toString.

If you're looking for template-like functionality to have re-usable string definitions to pass around and leverage, you should consider the Groovy template engine.

see http://groovy.codehaus.org/Groovy+Templates

Upvotes: 3

Another way is to use the in keyword:

groovy:000> t = "hello"
===> hello
groovy:000> t in String
===> true
groovy:000> "${t}" in GString
===> true

The in keyword is the membership operator, and gets translated to an isCase call on the class:

groovy:000> String.isCase(t)
===> true
groovy:000> GString.isCase("${t}")
===> true

Upvotes: 19

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28757

Instanceof tests should work:

assert "fasd" instanceof String
assert "${this}" instanceof GString

Upvotes: 44

Related Questions