为什么只使用@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)
解决方法
这是旧版
question的反转.当静态编译时,项是List类型,当没有静态编译时,类型是NullObject,它以零安全的方式检索迭代器.这是微不足道的证明.
这有效
class GroovyEach { static void main(String[] args) { List items = null (org.codehaus.groovy.runtime.NullObject) items } }
这与[静态类型检查]失败 – Inconvertible类型:无法将java.util.List强制转换为org.codehaus.groovy.runtime.NullObject
@groovy.transform.CompileStatic class GroovyEach { static void main(String[] args) { List items = null (org.codehaus.groovy.runtime.NullObject) items } }