相信大家都看过这样的代码。或多或少,最近因为项目中对接的是将null转换成了"null",而引起的问题也不少。
public static void main(String[] args)
{
Integer nullTest = null;
if (null == null)
{
System.out.println(true);
}
System.out.println(String.valueOf(nullTest));
System.out.println(String.valueOf(null));
}
这边写了个简单的不能再简单的测试类。
System.out.println(String.valueOf(nullTest));
会将转换成"null"。
System.out.println(String.valueOf(null));
会报空指针。
点开jdk中String.valueOf,看了下
/**
* Returns the string representation of the <code>Object</code> argument.
*
* @param obj an <code>Object</code>.
* @return if the argument is <code>null</code>, then a string equal to
* <code>"null"</code>; otherwise, the value of
* <code>obj.toString()</code> is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
如果传入对象为null,返回"null",如果不为null,直接toString。
但是为什么直接传
System.out.println(String.valueOf(null));
就会空指针呢,这就引发了null到底是个什么东西的想法,难道他不是继承自object?还是编译器不知道他的类型就默认的认为不是null了?