加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么String.valueOf(null)引起空指针异常?

发布时间:2020-12-14 05:18:55 所属栏目:Java 来源:网络整理
导读:为什么String.valueOf(null)引起空指针异常?其中预期的行为是返回“null”字符串. String x = null; System.out.println(String.valueOf(x)); 这给出一个“null”字符串.但 System.out.println(String.valueOf(null)); 将导致空指针异常. 解决方法 因为Stri
为什么String.valueOf(null)引起空指针异常?其中预期的行为是返回“null”字符串.
String x = null;
    System.out.println(String.valueOf(x));

这给出一个“null”字符串.但

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

将导致空指针异常.

解决方法

因为String.valueOf(null)选择带有char []参数的重载方法,然后在新的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 []是最具体的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读