問(wèn)題描述
我發(fā)現(xiàn)了一些奇怪的異常:
I found some strange exception:
java.lang.ClassCastException: java.lang.Integer
cannot be cast to java.lang.String
這怎么可能?每個(gè)對(duì)象都可以轉(zhuǎn)換為字符串,不是嗎?
How it can be possible? Each object can be casted to String, doesn't it?
代碼是:
String myString = (String) myIntegerObject;
謝謝.
推薦答案
為什么這是不可能的:
因?yàn)?String 和 Integer 不在同一個(gè) Object 層次結(jié)構(gòu)中.
Because String and Integer are not in the same Object hierarchy.
Object
/
/
String Integer
您正在嘗試的轉(zhuǎn)換僅在它們位于同一層次結(jié)構(gòu)中時(shí)才有效,例如
The casting which you are trying, works only if they are in the same hierarchy, e.g.
Object
/
/
A
/
/
B
在這種情況下,(A) objB
或 (Object) objB
或 (Object) objA
將起作用.
In this case, (A) objB
or (Object) objB
or (Object) objA
will work.
因此正如其他人已經(jīng)提到的,將整數(shù)轉(zhuǎn)換為字符串使用:
Hence as others have mentioned already, to convert an integer to string use:
String.valueOf(integer)
,或 Integer.toString(integer)
表示原語(yǔ),
或
Integer.toString()
用于對(duì)象.
這篇關(guān)于為什么不能在 Java 中將 Integer 轉(zhuǎn)換為 String?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!