举例说明这一点:
public class Chain {
private Chain chain;
public Chain returnChain() {
return chain;
}
public void addChain(Chain chain) {
this.chain=chain;
}
public String toString() {
return "Hello!";
}
public static void main(String[] args) {
Chain c1 = new Chain();
c1.addChain(new Chain());
System.out.println(c1.returnChain().returnChain().returnChain().returnChain());
}
}
这显然会抛出NullPointerException. (我知道如何更改代码以明确链接的哪一部分抛出NullPointerException,但我想用现有代码来解决这个问题.)
最佳答案
在典型NPE的堆栈跟踪中,您将获得它所发生的行号.假设System.out.println(c1.returnChain().returnChain().returnChain().returnChain());在第144行(只是随机选取)你的NPE堆栈跟踪应该类似于:
原文链接:/java/438001.htmljava.lang.NullPointerException
at your.package.Chain(Chain.java:144)
我写了这个小例子:
package bla;
public class Something {
public static int count = 0;
public Something get() {
if(count == 2) {
return null;
}
++count;
return new Something();
}
public static void main(String[] args){
Something something = new Something();
Something test = something.get()
.get()
.get()
.get() // Should throw NPE
.get()
.get();
}
}
它给了我NPE说:在bla.Something.main(Something.java:18) – 确切地说NPE在链中发生的地方.
屏幕截图……