前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2018-10-28 String.valueOf(null) 会报空指针异常

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

作者头像
Albert陈凯
发布2018-12-04 15:08:17
6220
发布2018-12-04 15:08:17
举报
文章被收录于专栏:Albert陈凯

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

代码语言:javascript
复制
    /**
     * 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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.10.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档