为什么空引用打印为“空"? [英] Why does null reference print as "null"

查看:35
本文介绍了为什么空引用打印为“空"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 println 中,这里 o.toString() 会抛出 NPE 而 o1 不会.为什么?

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	est-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

}

只看main方法,你可以看到感兴趣的行是Code是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() 的字节码.这里 onull,因此任何对 null 方法调用的尝试都会导致 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() 将使用 nulls:

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.

这篇关于为什么空引用打印为“空"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆