Java:如何检查对象是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2033088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How to check if object is null?
提问by Niko Gamulin
I am creating an application which retrieves images from the web. In case the image cannot be retrieved another local image should be used.
我正在创建一个从网络检索图像的应用程序。如果无法检索图像,则应使用另一个本地图像。
While trying to execute the following lines:
在尝试执行以下几行时:
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable.equals(null)) {
drawable = getRandomDrawable();
}
The line if(drawable.equals(null)) throws an exception if drawable is null.
如果 drawable 为 null,则 if(drawable.equals(null)) 行会引发异常。
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())?
有谁知道应该如何检查 drawable 的值,以便在它为 null 的情况下不抛出异常并检索本地图像(执行 drawable = getRandomDrawable())?
采纳答案by deamon
Edited Java 8 Solution:
编辑的 Java 8 解决方案:
final Drawable drawable =
Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
.orElseGet(() -> getRandomDrawable());
You can declare drawable
final
in this case.
drawable
final
在这种情况下,您可以声明。
As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.
正如 Chasmo 指出的那样,Android 目前不支持 Java 8。因此,此解决方案仅适用于其他情况。
回答by Thomas
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable == null) {
drawable = getRandomDrawable();
}
The equals()
method checks for valueequality, which means that it compares the contentsof two objects. Since null
is not an object, this crashes when trying to compare the contents of your object to the contents of null
.
该equals()
方法检查值是否相等,这意味着它比较两个对象的内容。由于null
不是对象,因此在尝试将对象的内容与null
.
The ==
operator checks for referenceequality, which means that it looks whether the two objects are actually the very same object. This does not require the objects to actually exist; two nonexistent objects (null
references) are also equal.
该==
运营商检查参考平等,它看起来,这意味着两个对象是否实际上是相同的对象。这不需要对象实际存在;两个不存在的对象(null
引用)也是相等的。
回答by Yatendra Goel
drawable.equals(null)
The above line calls the "equals(...)" method on the drawable object.
上面这行调用了可绘制对象上的“equals(...)”方法。
So, when drawable is not null and it is a real object, then all goes well as calling the "equals(null)" method will return "false"
因此,当 drawable 不为 null 并且它是一个真实对象时,一切顺利,调用“equals(null)”方法将返回“false”
But when "drawable" is null, then it means calling the "equals(...)" method on null object, means calling a method on an object that doesn't exist so it throws "NullPointerException"
但是当“drawable”为空时,则意味着在空对象上调用“equals(...)”方法,意味着在不存在的对象上调用方法所以它抛出“NullPointerException”
To check whether an object exists and it is not null, use the following
要检查对象是否存在且不为空,请使用以下命令
if(drawable == null) {
...
...
}
In above condition, we are checking that the reference variable "drawable" is null or contains some value (reference to its object) so it won't throw exception in case drawable is null as checking
在上述条件下,我们正在检查引用变量“drawable”是否为空或包含一些值(对其对象的引用),因此在检查时不会抛出异常,以防 drawable 为空
null == null
is valid.
已验证。
回答by outofcoffee
I use this approach:
我使用这种方法:
if (null == drawable) {
//do stuff
} else {
//other things
}
This way I find improves the readability of the line - as I read quickly through a source file I can see it's a null check.
我发现通过这种方式提高了该行的可读性 - 当我快速阅读源文件时,我可以看到它是一个空检查。
With regards to why you can't call .equals()
on an object which may be null
; if the object reference you have (namely 'drawable') isin fact null
, it doesn't point to an object on the heap. This means there's no object on the heap on which the call to equals()
can succeed.
关于为什么你不能调用.equals()
一个可能是的对象null
;如果你有(也就是“绘制”)的对象引用是在事实上null
,它并不指向堆中的对象。这意味着堆上没有equals()
可以成功调用的对象。
Best of luck!
祝你好运!
回答by Tom R
It's probably slightly more efficient to catch a NullPointerException. The above methods mean that the runtime is checking for null pointers twice.
捕获 NullPointerException 可能稍微更有效。上述方法意味着运行时检查空指针两次。
回答by heapuser
if (yourObject instanceof yourClassName)
will evaluate to false
if yourObject
is null
.
if (yourObject instanceof yourClassName)
将评估为false
if yourObject
is null
。
回答by Bala
Use google guava libsto handle is-null-check (deamon's update)
使用google guava libs处理 is-null-check(守护进程的更新)
Drawable drawable = Optional.of(Common.getDrawableFromUrl(this, product.getMapPath())).or(getRandomDrawable());
回答by Eddie B
DIY
DIY
private boolean isNull(Object obj) {
return obj == null;
}
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (isNull(drawable)) {
drawable = getRandomDrawable();
}
回答by schlebe
Just to give some ideas to oracle Java source developer :-)
只是给 oracle Java 源代码开发人员一些想法:-)
The solution already exists in .Net and is more very more readable !
该解决方案已经存在于 .Net 中,并且更具可读性!
In Visual Basic .Net
在 Visual Basic .Net 中
Drawable drawable
= If(Common.getDrawableFromUrl(this, product.getMapPath())
,getRandomDrawable()
)
In C#
在 C# 中
Drawable drawable
= Common.getDrawableFromUrl(this, product.getMapPath()
?? getRandomDrawable();
These solutions are powerful as Optional Java solution (default string is only evaluated if original value is null) without using lambda expression, just in adding a new operator.
这些解决方案作为 Optional Java 解决方案非常强大(仅当原始值为 null 时才计算默认字符串),而无需使用 lambda 表达式,只需添加一个新的运算符。
Just to see quickly the difference with Java solution, I have added the 2 Java solutions
只是为了快速查看与 Java 解决方案的区别,我添加了 2 个 Java 解决方案
Using Optional in Java
在 Java 中使用 Optional
Drawable drawable =
Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
.orElseGet(() -> getRandomDrawable());
Using { } in Java
在 Java 中使用 { }
Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable != null)
{
drawable = getRandomDrawable();
}
Personally, I like VB.Net but I prefer ?? C#
or if {}
solution in Java ... and you ?
就我个人而言,我喜欢 VB.Net,但我更喜欢Java?? C#
或if {}
解决方案......你呢?