How to trace a NullPointerException in a chain of getters

后端 未结 11 1563
谎友^
谎友^ 2020-12-03 06:46

If I get a NullPointerException in a call like this:

someObject.getSomething().getSomethingElse().
    getAnotherThing().getYetAnotherObject().getValue();
         


        
11条回答
  •  借酒劲吻你
    2020-12-03 07:45

    Here's how to find the bug, using Eclipse.

    First, set a breakpoint on the line:

    someObject.getSomething().getSomethingElse().
    getAnotherThing().getYetAnotherObject().getValue();
    

    Run the program in debug mode, allow the debugger to switch over to its perspective when the line is hit.

    Now, highlight "someObject" and press CTRL+SHIFT+I (or right click and say "inspect").

    Is it null? You've found your NPE. Is it non-null? Then highlight someObject.getSomething() (including the parenthesis) and inspect it. Is it null? Etc. Continue down the chain to figure out where your NPE is occurring, without having to change your code.

提交回复
热议问题