java是否可以从堆栈跟踪中区分哪个部分为空?
当我有一种方法时,比如:
public class Tttttt {
public Thing getThingBy(String name) {
return aaa.getThingBy(name);
}
}
然后我在日志中看到NPE
Caused by java.lang.NullPointerException
at xxx.yyy.Tttttt.getThingBy(SourceFile:666)
而且666
符合方法定义,那么我可以说name
是null
还是aaa
是null
# 1 楼答案
在这种情况下
aaa
是null
name
也可以是null
,但它将作为参数传递给getThingBy
,如果在堆栈跟踪中抛出异常,那么堆栈跟踪中会有更多条目# 2 楼答案
这是一个糟糕的例子
aaa
肯定是空的。将null参数传递给该方法不会引发任何异常。即使该方法确实调用了自身,您也会在stacktrace中看到这一点假设它确实再次被呼叫,而你在同一条线上使用了
aaa.someMethod(name.length())
。然后,您可能仍然能够根据stacktrace中提到的类类型和方法来确定变量,与Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
相比,这个问题at xxx.yyy.Tttttt.getThingBy