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

你可能感兴趣的:(2018-10-28 String.valueOf(null) 会报空指针异常)