在Java中检查空值的最佳方法是什么? [英] Best way to check for null values in Java?
本文介绍了在Java中检查空值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在调用对象的函数之前,我需要检查对象是否为null,以避免抛出 NullPointerException
。
Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException
.
最好的方法是什么?我考虑过这些方法。
哪一个是Java的最佳编程习惯?
What is the best way to go about this? I've considered these methods.
Which one is the best programming practice for Java?
// Method 1
if (foo != null) {
if (foo.bar()) {
etc...
}
}
// Method 2
if (foo != null ? foo.bar() : false) {
etc...
}
// Method 3
try {
if (foo.bar()) {
etc...
}
} catch (NullPointerException e) {
}
// Method 4 -- Would this work, or would it still call foo.bar()?
if (foo != null && foo.bar()) {
etc...
}
推荐答案
方法4最好。
if(foo != null && foo.bar()) {
someStuff();
}
将使用short-circuit evaluation ,意味着如果逻辑AND
的第一个条件为false,则结束。
will use short-circuit evaluation, meaning it ends if the first condition of a logical AND
is false.
这篇关于在Java中检查空值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文