gpt4 book ai didi

java - 为什么 String.valueOf(null) 会导致空指针异常?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:09:52 24 4
gpt4 key购买 nike

为什么 String.valueOf(null) 会导致空指针异常?预期行为是返回“空”字符串。

String x = null;
System.out.println(String.valueOf(x));

这给出了一个“空”字符串。但是

System.out.println(String.valueOf(null));

会导致空指针异常。

最佳答案

因为 String.valueOf(null) 选择带有 char[] 参数的重载方法,然后在 new String(null) 构造函数。这个选择是在编译时做出的。

如果你想显式地使用带有 Object 参数的重载方法,使用:

String.valueOf((Object) null)

请注意,没有采用 String 参数的重载方法 - 在第一种情况下调用的方法采用 Object

引用JLS :

15.12.2 Compile-Time Step 2: Determine Method Signature

The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments. 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.

所有方法都适用,所以我们去:

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.

感谢 polygenelubricants - 只有两个重载方法接受一个对象 - char[]Object - char[] 是最具体的.

关于java - 为什么 String.valueOf(null) 会导致空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4042675/

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