2018-10-28 String.valueOf(null) 会报空指针异常

Why 源代码里面明明检查了null

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

    /**
     * Returns the string representation of the {@code char} array
     * argument. The contents of the character array are copied; subsequent
     * modification of the character array does not affect the returned
     * string.
     *
     * @param   data     the character array.
     * @return  a {@code String} that contains the characters of the
     *          character array.
     */
    public static String valueOf(char data[]) {
        return new String(data);
    }

答案在这里:

https://stackoverflow.com/questions/4042675/why-string-valueofnull-is-causing-null-pointer-exception

15.12.2.5 Choosing the Most Specific Method

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

char[] 也是Object 所以先选char[]

还有更详细的解释和案例
https://stackoverflow.com/questions/3131865/why-does-string-valueofnull-throw-a-nullpointerexception

A char[] is-an Object, but not all Object is-a char[]. Therefore, char[] is more specific than Object, and as specified by the Java language, the String.valueOf(char[]) overload is chosen in this case.

其实我也看不懂英文,但我有谷歌翻译,当年我开始学习的时候,怎么没有这么好用的工具。

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,172评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 14,291评论 3 20
  • 很有趣 不是吗? 艺术家都喜欢画自画像 不一定是自恋 而是 因为自己是自己 最好的模特 对着镜子画 把自己画胖了一...
    烨然v阅读 1,198评论 0 0
  • 看到报道说俄罗斯的雪最深20米! 好想去体验一下,纯洁而又神秘的地方啊!
    潇潇雨歇歇阅读 1,297评论 0 0
  • 光与暗 交替希望与自由 黄昏 心的躁动 破晓 魂的安定 雨 光暗的协奏 风 夜梦的骤离 岁月 风华的寂灭 真实 死...
    沐溯流光阅读 1,283评论 0 2

友情链接更多精彩内容