美文网首页
Java——toString()

Java——toString()

作者: 远o_O | 来源:发表于2017-06-08 12:49 被阅读18次

总是有人说,打印一个对象的时候,会自动调用一个对象的toString方法,但是。。。

  • 一个null,在被打印时,根本不会抛出NullPointerException,而是奇怪的打印出“null”。
@org.junit.Test
    public void test4(){
        Object string = null;
        System.out.println(string);
    }

运行结果:

image.png
  • 这是因为System.out.println()方法,会进行判空操作:
    /**
     * 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);
    }

    /**
     * Prints an object.  The string produced by the <code>{@link
     * java.lang.String#valueOf(Object)}</code> method is translated 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      obj   The <code>Object</code> to be printed
     * @see        java.lang.Object#toString()
     */
    public void print(Object obj) {
        write(String.valueOf(obj));
    }

跟进去valueOf吧:

    /**
     * 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();
    }

相关文章

网友评论

      本文标题:Java——toString()

      本文链接:https://www.haomeiwen.com/subject/eonzfxtx.html