在任何情况下,当`foo`确实为空时,`foo == null`可能是假的?

时间:2016-10-20 18:03:58

标签: java null

我正在调试一个旨在优雅处理foo null个案的应用程序。但是,在从生产中检查日志时,在NullPointerException之后,尝试访问foo方法时,会优先处理该方法。

看起来像这样

if (foo == null) {
    throw new GracefulException();
}

Bar bar = foo.getBar();

使用该代码时,调用NullPointerException时生产中出现foo.getBar()

我的问题很简单:有没有人听说过这样的时髦行为,甚至可能发生?如果是这样,可能导致什么呢?

3 个答案:

答案 0 :(得分:7)

检查调用堆栈;可能来自getBar()内部。

此外,如果foo不是局部变量,则某些其他线程可能会在if之后将其设置为空。

答案 1 :(得分:1)

No. foo == null can never be false, if foo is null.

There could be these possible cases:

  1. Your application is multi-threaded and foo is a shared field that is not synchronized properly. If this is the case, then synchronization is required. As foo is a local variable, this case is not applicable here.
  2. Exception is coming from inside foo.getBar(). This case can be easily identified by the stack trace getting generated. Check if the method name is present in the stack trace.

For example, consider below code:

public class Temp {
    public static void main(String[] args) {
        new Temp().functionA();
    }

    void functionA() {
        Foo foo = new Foo();
        //foo = null; //Line 1
        String str = foo.getBar();
    }
}

class Foo {
    Object x = new Object();

    public String getBar() {
        //x = null; //Line 2
        return x.toString();
    }
}

If foo is null (Line 1 not commented), stack trace would be like:

Exception in thread "main" java.lang.NullPointerException
at Temp.functionA(Temp.java:9)
at Temp.main(Temp.java:3)

If x is null (Line 2 not commented), stack trace would be like:

Exception in thread "main" java.lang.NullPointerException
at Foo.getBar(Temp.java:16)
at Temp.functionA(Temp.java:8)
at Temp.main(Temp.java:3)

答案 2 :(得分:1)

如果堆栈跟踪中提到foo.getBar(),则会在该方法中抛出异常,并且您在错误的位置查找。

如果堆栈跟踪的顶部是包含此foo.getBar()次呼叫的方法,则foonull

既然你写了foo是一个局部变量,由于某些其他线程的干扰,这是而不是 - 另一个线程永远不能设置局部变量的值(大多数它可以做正在修改它的内容。

  • 检查检查和方法调用之间是否有foonull的语句设置。
  • 检查是否无法避免检查(即检查不在条件块中)
  • 检查检查和方法调用之间是否没有捕获阻止GracefulException