@CompileStatic给出NullPointerException

时间:2015-03-26 17:29:25

标签: groovy

为什么只使用@CompileStatic进行注释会使下面的代码产生NullPointerException?

class GroovyEach {
    static def main(args) {
        List items = null

        items.each {
            println 'hello'
        }

    }
}

下面的代码给出了异常。

import groovy.transform.CompileStatic

@CompileStatic
class GroovyEach {
    static def main(args) {
        List items = null

        items.each {
            println 'hello'
        }

    }
}

堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
    at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1372)
    at trial.GroovyEach.main(GroovyEach.groovy:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

1 个答案:

答案 0 :(得分:3)

这是旧版question的反面。静态编译时,items的类型为List,当不静态编译时,类型为NullObject,它以零安全的方式检索迭代器。这很容易证明。

这有效

class GroovyEach {
    static void main(String[] args) {
        List items = null
        (org.codehaus.groovy.runtime.NullObject) items
    }
}

此操作因[Static type checking] - Inconvertible types: cannot cast java.util.List to org.codehaus.groovy.runtime.NullObject

而失败
@groovy.transform.CompileStatic
class GroovyEach {
    static void main(String[] args) {
        List items = null
        (org.codehaus.groovy.runtime.NullObject) items
    }
}