1. 程式人生 > >說說JDK中的String.valueOf(null)?第一次遇到

說說JDK中的String.valueOf(null)?第一次遇到

1.第一次遇到的是時候 死活不理解為什麼?

String valueOf = String.valueOf(map.get("fkfs"));
if (valueOf != null ) {
        order.setFkfs(PayStyle.valueOf(String.valueOf(map.get("fkfs"))));// 取值
 }

程式碼 map.get("fkfs") 取出來是null

轉換為下面的

Object obj = null;
if(String.valueOf(obj)!=null){
   //肯定會走到這裡面來
 System.out.println(String.valueOf(obj));
}

System.out.println(String.valueOf(null));//拋異常

2.第一個輸出“null”,沒錯,不是空物件null也不是空串“”,而是一個字串!!包含四個字母n-u-l-l的字串,但是,第二個輸出,拋空指標異常了。

 /**
 2      * Returns the string representation of the <code>Object</code> argument.
 3      *
 4      * @param   obj   an <code>Object</code>.
 5      * @return  if the argument is <code>null</code>, then a string equal to
 6      *          <code>"null"</code>; otherwise, the value of
 7      *          <code>obj.toString()</code> is returned.
 8      * @see     java.lang.Object#toString()
 9      */
10     public static String valueOf(Object obj) {
11     return (obj == null) ? "null" : obj.toString();
12     }

很簡單的說法 如果物件為空,就返回字串的"null" 不為空就呼叫toString方法。

3.

再來說第二個:

第二個和第一個的不同,是java對過載的不同處理導致的。

基本型別不能接受null入參,所以接受入參的是物件型別,如下兩個:

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[]入參這個過載方法。

下面看這個方法:

/**
 2      * Returns the string representation of the <code>char</code> array
 3      * argument. The contents of the character array are copied; subsequent
 4      * modification of the character array does not affect the newly
 5      * created string.
 6      *
 7      * @param   data   a <code>char</code> array.
 8      * @return  a newly allocated string representing the same sequence of
 9      *          characters contained in the character array argument.
10      */
11     public static String valueOf(char data[]) {
12     return new String(data);
13     }

4.上面是 直 接new String的,再看new String的實現:

 1     /**
 2      * Allocates a new {@code String} so that it represents the sequence of
 3      * characters currently contained in the character array argument. The
 4      * contents of the character array are copied; subsequent modification of
 5      * the character array does not affect the newly created string.
 6      *
 7      * @param  value
 8      *         The initial value of the string
 9      */
10     public String(char value[]) {
11     this.offset = 0;
12     this.count = value.length;
13     this.value = StringValue.from(value);
14     }

那麼上面的程式碼第12行就會報異常了,所以的話不能傳入引數null;

希望遇到此現象的人別再迷途

5.本文參考部落格園的文章