gpt4 book ai didi

java - Java中的 "(Object)null"和 "null"有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 20:28:12 25 4
gpt4 key购买 nike

看看下面的例子:

class nul
{
public static void main (String[] args)
{
System.out.println (String.valueOf((Object)null));
System.out.println (String.valueOf(null));
}
}

第一个 println 写入 null 但第二个抛出 NullPointerException

为什么只有第二行值得异常(exception)?而这两个null有什么区别呢? Java中有real nullfake null吗?

最佳答案

第一次调用将调用 String.valueOf(Object)方法,因为您已将 null 显式类型转换为 Object 引用。相反,第二个将调用重载的 String.valueOf(char[])方法,因为对于 null 参数,char[]Object 更具体。

此方法还有其他接受原始参数的重载版本,但它们不是 null 参数的有效匹配项。

来自 JLS §15.12.2 :

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.

A method is applicable if it is either applicable by subtyping (§15.12.2.2), applicable by method invocation conversion (§15.12.2.3), or it is an applicable variable arity method (§15.12.2.4).

[...]

If several applicable methods have been identified during one of the three phases of applicability testing, then the most specific one is chosen, as specified in section §15.12.2.5.

现在查看这两种方法的源代码:

// This won't throw NPE for `obj == null`
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

// This will throw `NPE` for `data == null`
public static String valueOf(char data[]) {
return new String(data);
}

关于java - Java中的 "(Object)null"和 "null"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19317083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com