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
  if(mapOfValues.containsKey(field.getName())){

//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.
field.setAccessible(true);

//Base on type set the field value
if(type.equalsIgnoreCase("String")){
          field.set(obj, fieldValue);
}else if(type.equalsIgnoreCase("Long") ||             
                type.equalsIgnoreCase("long")){
    field.set(obj, Long.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Short") || 
               type.equalsIgnoreCase("short")){
    field.set(obj, Short.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Integer") || 
               type.equalsIgnoreCase("int")){
    field.set(obj, Integer.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Double") || 
               type.equalsIgnoreCase("double")){
    field.set(obj, Double.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Float") || 
               type.equalsIgnoreCase("float")){
    field.set(obj, Float.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("Boolean") || 
               type.equalsIgnoreCase("boolean")){
    field.set(obj, Boolean.valueOf(fieldValue));
}else if(type.equalsIgnoreCase("char") || 
               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