Java:如何检查对象是否为空? [英] Java: How to check if object is null?
问题描述
我正在创建一个从Web检索图像的应用程序.如果无法检索到图像,则应使用其他本地图像.
I am creating an application which retrieves images from the web. In case the image cannot be retrieved another local image should be used.
尝试执行以下行时:
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable.equals(null)) {
drawable = getRandomDrawable();
}
如果drawable为null,则if(drawable.equals(null))行会引发异常.
The line if(drawable.equals(null)) throws an exception if drawable is null.
有人知道应该如何检查drawable的值,以免在它为null的情况下不引发异常并检索本地图像(执行drawable = getRandomDrawable())?
Does anyone know how should the value of drawable be checked in order not to throw an exception in case it is null and retrieve the local image (execute drawable = getRandomDrawable())?
推荐答案
已编辑的Java 8解决方案:
final Drawable drawable =
Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
.orElseGet(() -> getRandomDrawable());
在这种情况下,您可以声明 drawable
final
.
You can declare drawable
final
in this case.
正如Chasmo指出的那样,Android目前不支持Java 8.因此,此解决方案仅在其他情况下可行.
As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.
这篇关于Java:如何检查对象是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!