I try to found, but all seems vague. I need convert Object o to Double. Is correct way first convert to String? Thanks.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
In Java version prior to 1.7 you cannot cast object to primitive type
You can cast an Object to a Double just fine
Beware, it can throw a ClassCastException if your object isn't a Double
Tried all these methods for conversion ->
If your Object represents a number, eg, such as an Integer, you can cast it to a Number then call the doubleValue() method.
You can use the instanceof operator to test to see if it is a double prior to casting. You can then safely cast it to a double. In addition you can test it against other known types (e.g. Integer) and then coerce them into a double manually if desired.
I tried this and it worked:
You can't cast an object to a
Double
if the object is not a Double.Check out the API.
particularly note
valueOf(double d);
and
valueOf(String s);
Those methods give you a way of getting a
Double
instance from a String or double primitive. (Also not the constructors; read the documentation to see how they work) The object you are trying to convert naturally has to give you something that can be transformed into a double.Finally, keep in mind that
Double
instances are immutable -- once created you can't change them.