在 Java 中检查空值的最佳方法是什么? [英] Best way to check for null values in Java?

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

问题描述

在调用对象的函数之前,我需要检查对象是否为空,以避免抛出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();
}

将使用短路评估,这意味着如果logical AND 的第一个条件为假.

will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.

这篇关于在 Java 中检查空值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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