D
D
DarkByte20152017-08-05 19:27:29
Java
DarkByte2015, 2017-08-05 19:27:29

How to convert an object to the desired type dynamically?

There is an object of a type not known in advance (from simple ones - strings, numbers, bools). In extreme cases, not an object, but a string (but an object is more convenient). And there is a Class to which this object must be converted (also from simple types). How to do it? Somehow through reflection, but have not yet found a way.

<T> T convert(Object value, Class<T> clazz) {
  return value; // ???
}

PS I know the necessary function in C# - Convert.ChangeType. I need something similar in java. If suddenly someone worked with both...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Myvrenik, 2017-08-06
@gim0

return (T) value;
Just be careful with ClassCastException

T
Truebober, 2017-08-06
@alexey_kip

Depends on what you need to convert. For example, if you want to convert an int to any other type, use the wrapper methods - Integer. For example, to convert int to double - Integer.doubleValue(), to float - Integer.floatValue().
If you need to cast a simple type to a String, use String.valueOf().
In general, java is strongly typed. You can't convert what you don't know, you don't know what.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question