问题
This morning I found an interesting question --- cast object to string check if valid and I found there are two types of answers. One is to cast an object to String, the other one is to get the string representation of that object instead (eg. using String.valueOf() or toString()). My questions are: what is the best practice? what is the difference between them?
Before I asked this questions, I found several existing questions which are relevant, but I didn't find one which answers my question. Please forgive me if I missed the important one and hope you don't mind pointing me to the answers.
Thank you,
回答1:
If the Object is not a String, a cast will throw a ClassCastException
at runtime. For example:
Object o = new Object();
String s = (String) o; //Exception here
The difference between the other two solutions (toString
vs. String.valueOf
) is in the case of a null object. toString
will throw an exception whereas String.valueOf()
will simply return "null"
:
Object o = null;
String s = String.valueOf(o); //s = "null";
String t = o.toString(); //NullPointerException
来源:https://stackoverflow.com/questions/17029719/casting-to-string-or-using-string-valueof-in-java