toString、String.valueOf、Objects.toString,(String) 對象轉爲String的四種方法比較

 

在java項目的實際開發和應用中,常常需要用到將對象轉爲String這一基本功能。常用的方法有 對象.toString(),Objects.toString(),強轉,String.valueOf(Object)等。

 

1)對象.toString()

    因爲所有java對象都繼承至Object,java.lang.Object類裏已有public方法.toString(),所以對任何嚴格意義上的java對象都可以調用此方法。但是,通常派生類會重寫Object裏的toString() 方法。調用該方法,需保證對象不是null值,否則將拋出NullPointerException異常。如果貿然地調用改變量的toString()方法,則可能引發NullPointerException。


2)Objects.toString()

    這是Java 7新增的一個Objects類(Java爲工具類的命名習慣是添加一個字母s),其中有靜態方法toString(Object obj)。這裏obj若爲null,Objects.toString(obj)將會返回“null”字符串。

其方法說明如下,可以看出實際調用的是 String.valueOf() 方法。

/**
     * Returns the result of calling {@code toString} for a non-{@code
     * null} argument and {@code "null"} for a {@code null} argument.
     *
     * @param o an object
     * @return the result of calling {@code toString} for a non-{@code
     * null} argument and {@code "null"} for a {@code null} argument
     * @see Object#toString
     * @see String#valueOf(Object)
     */
    public static String toString(Object o) {
        return String.valueOf(o);
    }

3)強轉

    使用這種方法時,需要注意的是類型必須能轉成String類型。因此最好用instanceof做個類型檢查,以判斷是否可以轉換。否則容易拋出ClassCastException異常。此外,需特別小心的是因定義爲Object 類型的對象在轉成String時語法檢查並不會報錯,這將可能導致潛在的錯誤存在。null可以強制轉換爲任何java類類型,(String)null也是合法的。


4)String.valueOf()

String類提供的將基本類型值轉爲String對象的靜態方法,返回刪除頭尾空白符的字符串。String.valueOf(Object obj)當這裏的obj是null,將返回“null”字符串。

其方法說明如下,可以看出實際調用的是 對象.toString() 方法。

 /**
     * Returns the string representation of the {@code Object} argument.
     *
     * @param   obj   an {@code Object}.
     * @return  if the argument is {@code null}, then a string equal to
     *          {@code "null"}; otherwise, the value of
     *          {@code obj.toString()} is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章