How to convert Object to “original” type Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to convert Object to “original” type without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the following code, where i get a HashMap<String,Object> which contains different datatypes as values (e.g. int, String, float) and want to cast the Object to its original type.

HashMap<String,Object> values = new HashMap<String,Object>;
values.put("Field1", 23);
values.put("Field2", "teststring");
values.put("Field3", 64.23f);

int a = (Integer)values.get("Field1");
String b = (String)values.get("Field2");
float c = (Float)values.get("Field3");

As you can see I know how to do this by typecasting, but is there a way to do this dynamically?

I know I can get the “original” type with values.get("Field3").getClass(); but I don’t know how to use it in order to solve my problem.

I have two ints in the query result and I want to know the sum of them. Therefore I have to cast the Objects to int and then build the sum. Next time I want to do the same thing, but instead of ints, the types are floats.

Answer

If I’ve correctly understood your problem, you should do something like this:

Object obj = values.get(fieldName);
if(obj instanceof Float){
  float f = (float) obj;
  // do what you need with a float
} else if(obj instanceof String){
  String s = (String) obj;
  // do what you need with a String
} ...

Types set and precedence depends on your task.

We are here to answer your question about How to convert Object to “original” type - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji