Java: How to extract the name/type of dereferenced object from NullPointerException
Here is my situation.
When developing a Java开发者_如何学JAVA application, you occasionally get a java.lang.NullPointerException
. You can print the stack trace and it will tell you the class and the line number where a null object was dereferenced. Typically, it is trivial to figure out which object might be null (you can always check for nullity of all the objects dereferenced in that statement).
Is it possible to know programmatically from the NullPointerException exactly which referenced object is null (if there are multiple different objects used in the same statement)?
An object cannot be null
only a reference can be null
. The simplest way to check which reference is null is to deference each value on a different line.
There is no object by definition. The reference is null.
Reading your question again and I think I mis-understood. I presume you mean you have something like:
if(ref1.method() && ref2.method()) {
....
}
and you want to know if ref1 or ref2 is null.
If so, then no. Split up the statement into separate lines.
No. You can't do that (in the general case). The reason is that Java (like most other languages) does not keep track of intermediate results.
In theory you could.. in practice you cant... i mean.. it is possible. Build you would have to either extend the JVM or try to find another difficult solution.
精彩评论