java string 空指针_java – 为什么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 []是最具体的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值