听说你有一个null要打印?

其实 null 这个东西,真是让人又爱又恨,悲喜参半的东西。
用的好了,能表征很多状态,并在程序中很好实现状态的传递,用的不好了,各种NPE问题可以把你烦死……

好吧,以上是题外话,那么这次问题的主旨在于,鉴于null这种关键字很大程度上丰富了我们的语义,并且随着JDK5之后装箱和拆箱的自动进行,null的出场概率更是越来越多。

但是随之而来一个问题就是,当我们想要打印一个null来表示该对象为null的时候,什么操作去处理才是安全可靠的呢?
本文的主旨主要就是对此做一个简单的备忘,以防之后模棱两可的时候又要去看很久,毕竟好记性不如烂笔头嘛,那么首先先把备忘的表格写上(希望大家补充和指教~ :D)

方法 结果
println(objectNull) 成功打印null
String.valueOf(objectNull) 成功打印null
StringBuider.append(objectNull) 成功打印null
ObjectNull = null; ObjectNull .toString() NPE
"any" + objectNull 成功打印null

以上就是一个简单的表格总结,那么为什么会产生这种原因呢?

具体原因分析

其实通过源码来看,就会发现,其实问题都非常的清晰了,以下对每个操作类型都给出了实现的片段,来佐证实际程序中的操作结果。

println(objectNull)

可以发现,该函数内部对null做了特殊处理,如果是null对象则处理成一个“null”的字符串,从而不会造成NPE问题。

    /**
     * Prints a string.  If the argument is <code>null</code> then the string
     * <code>"null"</code> is printed.  Otherwise, the string's characters are
     * converted into bytes according to the platform's default character
     * encoding, and these bytes are written in exactly the manner of the
     * <code>{@link #write(int)}</code> method.
     *
     * @param      s   The <code>String</code> to be printed
     */
    public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(s);
    }

String.valueOf(objectNull)
    /**
     * Returns the string representation of the <code>Object</code> argument.
     *
     * @param   obj   an <code>Object</code>.
     * @return  if the argument is <code>null</code>, then a string equal to
     *          <code>"null"</code>; otherwise, the value of
     *          <code>obj.toString()</code> is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

StringBuider.append(objectNull) :

虽然StringBuilder的append方法有比较多的重载方法,但是总体来说,都对null对象做了特殊的处理,方式主要有两种:1.调用String.valueOf方法(具体实现原理如上所示);2.对null的字符串对象直接调整为打印“null”

    //  (笔者注): part1
    public StringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }

    // (笔者注): part2 
    /**
     * Appends the specified string to this character sequence.
     * <p>
     * The characters of the {@code String} argument are appended, in
     * order, increasing the length of this sequence by the length of the
     * argument. If {@code str} is {@code null}, then the four
     * characters {@code "null"} are appended.
     * <p>
     * Let <i>n</i> be the length of this character sequence just prior to
     * execution of the {@code append} method. Then the character at
     * index <i>k</i> in the new character sequence is equal to the character
     * at index <i>k</i> in the old character sequence, if <i>k</i> is less
     * than <i>n</i>; otherwise, it is equal to the character at index
     * <i>k-n</i> in the argument {@code str}.
     *
     * @param   str   a string.
     * @return  a reference to this object.
     */
    public AbstractStringBuilder append(String str) {
        if (str == null) str = "null";
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }

ObjectNull = null; ObjectNull .toString() :

如果没有主动的重写Object的toString方法,则会调用Object(所有类的父类)中的toString方法,可见这种方法是没有对null做特殊处理的,所以如果如Java中鼓励的那样,我们最好针对自己的对象重写toString来避免这种NPE的问题。
其次,我们可以挑选装箱类型来看一下,也会发现,因为有自动拆箱的过程存在,也会存在NPE问题,所以这种场景下也需要注意。

    // object
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

    // Integer
    public String toString() {
        return toString(value);
    }

"any" + objectNull :

参考这篇文章《在java中,字符串的加法是如何实现的?》,可以发现实际上这种加号的实现原理其实就是基于StringBuilder的,也就很好理解为什么加号会有这种表现了。

对于加号的字符串拼接含义

小结

因此,使用toString的方式来打印null是存在问题的,而其它的几种方式都得益于方法内部的兼容处理,可以正常的处理null的打印。
特别有意思的是,+号的处理,实际上是通过StringBuilder来实现的,不得不感慨一下这种复用思想的使用,结合java中string在堆中的实际处理情况来理解,感觉也是一个非常有意思的处理方式。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,780评论 18 399
  • 我很抱歉 我有时候会骚扰你 以后绝对不会 发给你一条信息 看你一条动态 与你有关的很多很多 我都不会多生心思 不打...
    五月sn阅读 68评论 0 0
  • 2012-08-12 过程和结局都有了 分手自己都觉得贪婪 悲伤我自己刻镌 微笑分你一半 斑驳的故事搁浅 没有可寻...
    一婉江南若孤芳阅读 504评论 0 3
  • “汗流浃背,吃一口夏日甜品,真是酣畅淋漓呀!”我惬意地感叹道。 “方禾夏,你知道吗,你是我见过最奇葩的女子。”林加...
    徐蜀旅阅读 412评论 0 0