Java 从 Object 到 long 到 String 的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17114946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Cast from Object to long to String
提问by Mastergeek
Here's the situation, I have an Object in a Map which I explicitly know to contain an instance of Long and I need to turn that value into a string but keep getting incompatible type errors. Here's what my code looks like:
这是这种情况,我在 Map 中有一个对象,我明确知道它包含一个 Long 的实例,我需要将该值转换为字符串,但不断收到不兼容的类型错误。这是我的代码的样子:
Map<String, Object> map = ...;
Object obj = new Long(31415L);
String str = Long.valueOf((long)map.get("id")); //Problem line
This gives:
这给出:
Inconvertible types.
Found : java.lang.Object
Required: long
Any suggestions as to how to get around this?
关于如何解决这个问题的任何建议?
回答by fge
Use, for instance:
使用,例如:
String.valueOf(map.get("id"))
The problem is that you try and cast an object to a primitive type. That cannot work.
问题在于您尝试将对象强制转换为原始类型。那行不通。
But since the values of your map will be Long
s anyway (collections cannot contain primitive types, save for specialized implementations such as found in GNU Trove), look at @BheshGurung's answer...
但是由于您的地图的值Long
无论如何都是s(集合不能包含原始类型,除了在 GNU Trove 中找到的特殊实现之外),请查看@BheshGurung 的答案...
回答by Bhesh Gurung
You can just do
你可以做
String str = map.get("id").toString();
回答by zee
You can use the toString function;
public String toString() {
return String.valueOf(map.get("id"))
}
String str = map.get("id").toString();
回答by technophiliac
You have 2 issues here:
你在这里有两个问题:
You created a *L*ong, not a *l*ong. Therefore you need to cast back to a *L*ong, not a *l*ong.
In order to get the String representation of a *L*ong you must call toString() on it.
您创建了 * L*ong,而不是 * l*ong。因此,您需要转换回 * L*ong,而不是 * l*ong。
为了获得 * L*ong的字符串表示,您必须对其调用 toString() 。
Use this:
String str = ((Long)map.get("id")).toString();
用这个:
String str = ((Long)map.get("id")).toString();