当前位置:  开发笔记 > 编程语言 > 正文

为什么我得到这个输出,但不要使用String

如何解决《为什么我得到这个输出,但不要使用String》经验,为你挑选了1个好方法。

如果你看看你看到的PrintWriter.println(Object)的Javadoc和源代码

/**
 * Prints an Object and then terminates the line.  This method calls
 * at first String.valueOf(x) to get the printed object's string value,
 * then behaves as
 * though it invokes {@link #print(String)} and then
 * {@link #println()}.
 *
 * @param x  The Object to be printed.
 */
public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (lock) {
        print(s);
        println();
    }
}

反过来,String.valueOf(Object)可以

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

所以你可以看到toString()为你而来.

正如文档中所述,您可以假设将来或其他实现中不会更改.即代码可能会更改,但记录的功能将始终保留.



1> Peter Lawrey..:

如果你看看你看到的PrintWriter.println(Object)的Javadoc和源代码

/**
 * Prints an Object and then terminates the line.  This method calls
 * at first String.valueOf(x) to get the printed object's string value,
 * then behaves as
 * though it invokes {@link #print(String)} and then
 * {@link #println()}.
 *
 * @param x  The Object to be printed.
 */
public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (lock) {
        print(s);
        println();
    }
}

反过来,String.valueOf(Object)可以

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

所以你可以看到toString()为你而来.

正如文档中所述,您可以假设将来或其他实现中不会更改.即代码可能会更改,但记录的功能将始终保留.

推荐阅读
携手相约幸福
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有