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

标签 java

为什么 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/

相关文章:

java - 尝试为文本字段设置文本

java - Spring 的 NumberFormat 线程安全

java - 使用 JPA 标准连接没有关系的表

java - 停止一系列方法而不返回 boolean 值

java - 在JAVA中获取二维数组并输出一维数组

java - List<E>.contains(Object),为什么?

java - Kotlin 中的 getDeclaredMethod?

java - 是否可以拦截所有 DataNucleus 的 JDO SQL 查询?

java - 在java代码中使用savedInstanceState来保存可重用的值

Java if-then 语句中的变量初始化