String.valueOf() vs. Object.toString()

后端 未结 10 769
挽巷
挽巷 2020-12-12 10:21

In Java, is there any difference between String.valueOf(Object) and Object.toString()? Is there a specific code convention for these?

10条回答
  •  甜味超标
    2020-12-12 10:45

    String.valueOf(Object) and Object.toString() are literally the same thing.

    If you take a look at the implementation of String.valueOf(Object), you'll see that String.valueOf(Object) is basically just a null-safe invocation of toString() of the appropriate object:

    Returns the string representation of the Object argument.
    
    Parameters:
        obj an Object.
    Returns:
        if the argument is null, then a string equal to "null"; 
        otherwise, the value of obj.toString() is returned.
    See also:
        Object.toString()
    
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
    

提交回复
热议问题