为什么Groovy没有捕获我的instanceof?

IAm*_*aja 5 groovy instanceof

在以下代码中:

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."
    }
}
Run Code Online (Sandbox Code Playgroud)

声明" 我完全不知道'str'是什么. "是什么打印.为什么,以及如何让Groovy看到它str是一个String(除了使String非空)?

Jef*_*own 9

因为str是null,这不是String.

instanceof关键字询问引用指向的对象,而不是引用类型.

编辑

试试这个...

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."
    }
}
Run Code Online (Sandbox Code Playgroud)