Monday, April 27, 2015

Populating Java object in a generic way using reflection

There is a need for reading data from text files/excel files and populate them into objects. Below is a way to handle such population of object in a generic way. This mechanism only works for primitive type. The user defined types need to be handled in the application specific way. The code sample uses reflection to achieve this

//Pass the object that needs to be populated with a map of key 
//value pair. The key is the field name and the value is the value.
//The map can be built by reading the input data. void buildObject(Object obj, Map<String,String> mapOfValues) throws InstantiationException, IllegalAccessException{

//Get all the fields of the Class of object
 Field fields[] = obj.getClass().getDeclaredFields();

//Iterate through each field
 for(Field field: fields){

  //Check is the filed is in map as a key

//Get the field name
String fieldValue = mapOfValues.get(field.getName());

   //Get the type
String type = field.getType().getSimpleName();

   //Making it accessible allows to see private stuff. By default
   //java compile time rules are applied.

//Base on type set the field value
          field.set(obj, fieldValue);
}else if(type.equalsIgnoreCase("Long") ||             
    field.set(obj, Long.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Short") || 
    field.set(obj, Short.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Integer") || 
    field.set(obj, Integer.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Double") || 
    field.set(obj, Double.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Float") || 
    field.set(obj, Float.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Boolean") || 
    field.set(obj, Boolean.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("char") || 
    field.set(obj, fieldValue.toCharArray()[0]);

At the end, the object will have its primitive and String data values filled in a generic way.

No comments:

Post a Comment