将Object转换成String类型的两种

一、将Object转换成String类型的两种方法(建议使用2):

1、强制转换(String)

2、String.valueOf()

二、各种情况对比:

1、

Object object = new Object();
object = 123123;
String str = (String)(object);
System.out.println(str);

结果:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
Object object = new Object();
object = 123123;
String str = String.valueOf(object);
System.out.println(str);

结果:
123123

2、

Object object = new Object();
object = "123123";
String str = (String)(object);
String str1 = String.valueOf(object);
System.out.println(str);
System.out.println(str1);

结果:
123123
123123

3、

Object object = null;
String str = (String)(object);
String str1 = String.valueOf(object);
System.out.println(str);
System.out.println(str1);

结果:
null
null

4、

Object object = new Object();
String str = (String)(object);
System.out.println(str);

结果:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String
Object object = new Object();
String str = String.valueOf(object);
System.out.println(str);

结果:
java.lang.Object@7eda2dbb

 

你可能感兴趣的:(java)