String x = null; System.out.println(String.valueOf(x));
这给出一个“null”字符串.但
System.out.println(String.valueOf(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 []是最具体的.