Why isn't Groovy catching my instance?
In the following code:
static void main(String[] args) {
String str
if(str instanceof String) {
println "'str' is a String!"
} else {
println "I have absolutely no idea what 'str' is."
}
}
The statement "I have absolutely no idea what" str "is. This is what it prints. Why and what can I do to make Groovy see what str
is a string (other than the fact that the string is not null)?
+3
source to share
1 answer
Because it str
is null, which is not String
.
The instanceof keyword asks for the referenced object, not the reference type.
EDIT
Try it...
static void main(args) {
String str = 'King Crimson Rocks!'
if(str instanceof String) {
println "'str' is a String!"
} else {
println "I have absolutely no idea what 'str' is."
}
}
+7
source to share