java Object t 强转String

Object reallyAString = "foo";

String str = (String) reallyAString;

Object reallyAString = "foo";

String str = reallyAString.toString();

Object reallyAString = "foo";

String str = String.valueOf(reallyAString);


源码分析:

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }


与object.toString()不同的是,如果被转换对象为null时,String.valueOf()不会抛出空指针异常,而是转换为字符串”null”. 
如果被转换对象不为null,则直接调用被转换对象的toString().


你可能感兴趣的:(java)