问题描述
在println中,这里o.toString()抛出NPE但是o1抛出NPE。为什么?
In println, here o.toString() throws NPE but o1, does not. Why?
public class RefTest {
public static void main(String[] args) {
Object o = null;
Object o1 = null;
System.out.println(o.toString()); //throws NPE
System.out.print(o1); // does not throw NPE
}
}
推荐答案
它可能有助于向您显示字节码。看一下你班级的以下 javap
输出:
It might help showing you the bytecode. Take a look at the following javap
output of your class:
> javap -classpath target\test-classes -c RefTest
Compiled from "RefTest.java"
public class RefTest extends java.lang.Object{
public RefTest();
Code:
0: aload_0
1: invokespecial #8; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: aconst_null
1: astore_1
2: aconst_null
3: astore_2
4: getstatic #17; //Field java/lang/System.out:Ljava/io/PrintStream;
7: aload_1
8: invokevirtual #23; //Method java/lang/Object.toString:()Ljava/lang/String;
11: invokevirtual #27; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
14: getstatic #17; //Field java/lang/System.out:Ljava/io/PrintStream;
17: aload_2
18: invokevirtual #33; //Method java/io/PrintStream.print:(Ljava/lang/Object;)V
21: return
}
只需查看主要方法,您就可以看到感兴趣的行是代码
是8和33。
Just looking at the main method, you can see the lines of interest are where Code
is 8 and 33.
代码8显示了调用 o.toString()
的字节码。这里 o
是 null
所以在 null $ c上进行方法调用的任何尝试都是如此$ c>结果为
NullPointerException
。
Code 8 shows the bytecode for you calling o.toString()
. Here o
is null
and so any attempt on a method invocation on null
results in a NullPointerException
.
代码18显示您的 null
将对象作为参数传递给 PrintStream.print()
方法。查看此方法的源代码将显示为什么不会导致NPE中的结果:
Code 18 shows your null
object being passed as a parameter to the PrintStream.print()
method. Looking at the source code for this method will show you why this does not result in the NPE:
public void print(Object obj) {
write(String.valueOf(obj));
}
和 String.valueOf()
将使用 null
s执行此操作:
and String.valueOf()
will do this with null
s:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
所以你可以看到有一个测试处理 null
,并阻止NPE。
So you can see there is a test there which deals with null
, and prevents an NPE.
这篇关于为什么空引用打印为“null”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!