为什么在这种情况下我不会在Groovy中获得NullPointerException? [英] Why don't I get a NullPointerException in Groovy in this case?
本文介绍了为什么在这种情况下我不会在Groovy中获得NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个测试代码:
def test = null
test.each {}
为什么我不会收到任何异常?
each 的实现尝试调用
iterator
方法它的目标以无效的方式。如果在空对象或没有迭代器
方法的对象上调用每个
,则不会发生任何事情。 我还没有看到源代码,但它可能看起来像这样§
Object each(Closure closure){
if(this?.respondsTo(iterator)){
def iterator = this.iterator()
while(iterator.hasNext(){
def item = iterator.next()
closure(item)
}
}
return this
§实际上,这种方法可能是用Java而不是Groovy编写的
I have this test code:
def test = null
test.each { }
Why don't I get any exception?
解决方案 The implementation of each
tries to call the iterator
method of it's target in a null-safe fashion. If each
is called on a null object, or an object without an iterator
method, nothing happens.
I haven't seen the source code, but it could look something like this§
Object each(Closure closure) {
if (this?.respondsTo("iterator")) {
def iterator = this.iterator()
while (iterator.hasNext() {
def item = iterator.next()
closure(item)
}
}
return this
}
§ In reality, this method is probably written in Java rather than Groovy
这篇关于为什么在这种情况下我不会在Groovy中获得NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文