Answer the question
In order to leave comments, you need to log in
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; // ???
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question