說說關於String.valueOf的這個坑。java
public class TestString { public static void main(String[] args){ Object obj = null; System.out.println(String.valueOf(obj)); System.out.println(String.valueOf(null)); } }
這段代碼,第一個輸出「null」,沒錯,不是空對象null也不是空串「」,而是一個字符串!!包含四個字母n-u-l-l的字符串...this
第二個輸出,咋一看沒差異,可是,第二個輸出,拋空指針異常了。指針
下面來分析分析緣由。code
先說第一個:對象
看第一個的源碼實現:字符串
/** * 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"...不爲空就調用toString方法。源碼
再來講第二個:string
第二個和第一個的不一樣,是java對重載的不一樣處理致使的。it
基本類型不能接受null入參,因此接受入參的是對象類型,以下兩個:io
String valueOf(Object obj)
String valueOf(char data[])
這兩個都能接受null入參,這種狀況下,java的重載會選取其中更精確的一個,所謂精確就是,重載方法A和B,若是方法A的入參是B的入參的子集,則,A比B更精確,重載就會選擇A。換成上面這兩個就是,char[]入參的比object的更精確,由於object包含char[],因此String.valueOf(null)是用char[]入參這個重載方法。
看看這個方法的實現:
/** * Returns the string representation of the <code>char</code> array * argument. The contents of the character array are copied; subsequent * modification of the character array does not affect the newly * created string. * * @param data a <code>char</code> array. * @return a newly allocated string representing the same sequence of * characters contained in the character array argument. */ public static String valueOf(char data[]) { return new String(data); }
直接new String的,再看new String的實現:
/** * Allocates a new {@code String} so that it represents the sequence of * characters currently contained in the character array argument. The * contents of the character array are copied; subsequent modification of * the character array does not affect the newly created string. * * @param value * The initial value of the string */ public String(char value[]) { this.value = Arrays.copyOf(value, value.length); }
第12行,入參爲null,null.length就報NPE了。
你們用的時候養成多看源碼實現的好習慣,能夠避免踩坑...