Groovy中的NullObject类的目的是什么? [英] What is the purpose of the NullObject class in Groovy?

查看:172
本文介绍了Groovy中的NullObject类的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Groovy五个小时,刚刚遇到 Groovy NullObject 。我阅读了Groovy 空对象模式的解释,但它没有涉及直接使用 NullObject 类;是 NullObject 仅仅是为像 NullTree NullJob ?在某些需要 String 的代码中,我得到了一个 NullObject ,这导致了一个很像 null 会有。 code>?或者,换句话说, NullObject 是否提供了常规 null 不会?

解决方案

它的目的是让一个 null 对象代替 null 关键字。


$ b 在普通的Java null 中是一个特殊的关键字,它用于表示引用isn' t附加到任何对象..这工作正常,但它不处理您尝试使用 null 引用做某些事情。



由于 null 引用不是对象,因此您无法对其执行任何操作,Java将引发 NullPointerException 。另一方面,如果你有一个 NullObject ,那么你的引用将指向这一个,而不是那个。当然,这个 NullObject 无法做任何事情,当你尝试调用一个方法时,什么都不会发生,但不会抛出任何异常,因为通过 NullObject 意味着没有任何对象,它被实现为一个明显的对象以避免这些情况。



所以groovy可以处理像 object这样的东西。.methodName() 。如果object是 null groovy将使用 NullObject ,这样这个隐式检查就会做类似的事情(也许这不是实际的实现,只是为了给你的想法)

  if(object instanceof NullObject)
return new NullObject();
else
return object.someMethod();

总之,需要克服使用 null 引用在Java中总是会导致 NullPointerException


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?

解决方案

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 a NullObject your reference will point to this one instead that to nothing.. of course this NullObject 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 althrough NullObject 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 a NullObject so that this implicit check will do something like (maybe this is not the actual implementation, is just to give you the idea)

if (object instanceof NullObject)
  return new NullObject();
else
  return object.someMethod();

In conclusion it is needed to overcome the fact that using a null reference in Java will always cause a NullPointerException.

这篇关于Groovy中的NullObject类的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆