Groovy 中 NullObject 类的用途是什么?
我已经使用 Groovy 五个小时了,刚刚遇到了 Groovy NullObject
。我阅读了 Groovy 空对象模式的解释,但它没有触及直接使用NullObject
类; NullObject
仅仅是为了成为 NullTree
和 NullJob
之类的基类吗?我在一些需要 String
的代码中得到了一个 NullObject
,它导致了一个失败,就像“常规”null
会发生的那样。
那么,NullObject
的用途是什么?或者,换句话来说,NullObject
提供了哪些“常规”null
不提供的值?
I've been using Groovy for all of five hours and just came across the Groovy NullObject
. I read the Groovy explanation of the Null Object Pattern, but it doesn't touch on the NullObject
class directly; is NullObject
merely intended to be a base class for things like NullTree
and NullJob
? I'm getting a NullObject
back in some code that expects a String
, and it's causing a failure much like a "regular" null
would have.
So, what is the purpose of NullObject
? Or, phrased differently, what value does NullObject
offer that "regular" null
doesn't?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它的目的是拥有一个 null 对象而不是
null
关键字。在普通的 Java 中,
null
是一个特殊的关键字,它用于表示引用未附加到任何对象。这工作正常,但它不能处理您尝试执行某些操作的情况null 引用。由于 null 引用不是一个对象,因此您无法对其执行任何操作,并且 Java 将抛出
NullPointerException
。另一方面,如果您有一个NullObject
,您的引用将指向这个,而不是指向任何内容。当然,当您'时,这个NullObject
无法执行任何操作如果你尝试调用它的方法,什么都不会发生,但也不会抛出异常,因为虽然NullObject
意味着“不存在任何对象”,但它被实现为一个具有明显后果的对象,以避免这些情况。这样 groovy 就可以处理诸如
object?.methodName()
之类的事情。如果对象为 null groovy 将使用NullObject
以便此隐式检查将执行类似的操作(也许这不是实际的实现,只是为了给您一个想法)结论是需要克服这样一个事实:在 Java 中使用 null 引用总是会导致
NullPointerException
。Its purpose is to have a null object instead that a
null
keyword.In normal Java
null
is a special keyword that it's used to mean that the reference isn't attached to any object.. this works fine but it doesn't handle situations in which you try to do something with a null reference.Since a null reference is not an object you can't do anything on it and Java will throw a
NullPointerException
. On the opposite hand if you have aNullObject
your reference will point to this one instead that to nothing.. of course thisNullObject
is not able to do anything, when you'll try to invoke a method on it nothing will happen but no exception will be thrown because althroughNullObject
means "absence of any object" it's implemented as an object with the obvious conseguence to avoid these situations.So that groovy can handle things like
object?.methodName()
. If object is null groovy will use aNullObject
so that this implicit check will do something like (maybe this is not the actual implementation, is just to give you the idea)In conclusion it is needed to overcome the fact that using a null reference in Java will always cause a
NullPointerException
.