How to convert Object to “original” type

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.

Leave a Reply

Your email address will not be published. Required fields are marked *