ObjectをStringタイプに変換する2種類

1310 ワード

一、ObjectをStringタイプに変換する2つの方法(推奨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