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

前端之家收集整理的这篇文章主要介绍了java – 为什么String.valueOf(null)引起空指针异常?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么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 []是最具体的.

原文链接:https://www.f2er.com/java/122923.html

猜你在找的Java相关文章