dimanche 12 novembre 2017

Custom reflection method for setting field

I'm fairly new to using reflection and am currently trying to implement a custom reflection util for setting fields. Looking at springboots ReflectionsTestUtils, I've got a mild understanding of how the setFields is done. I'm currently trying to implement that by taking an Object and an ImmutableMap as parameters.

The thought is to match the Field/Key value from the hashmap with a field that exists in the object.

Not sure if i'm heading the right way here and would appreciate all the tips given:

    public static void setField(Object object, ImmutableMap<String, Object> map)
  throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
      if (object instanceof Object) {
        Field[] fields = object.getClass().getDeclaredFields();

        for (Field aField : fields) {
         for (Map.Entry<String, Object> entry : map.entrySet()) {
          if (entry.getKey() instanceof Object) {
           String value = entry.getKey();
           checkPrimitiveValue(aField, object, value);
         }
        }
       }
    }

}

   private static void checkPrimitiveValue(Field field, Object object, String value) throws IllegalArgumentException, IllegalAccessException {
// Find out Primitive and parse the string to correct value
if (field.getType() == boolean.class) {
  field.setAccessible(true);
  field.set(object, Boolean.parseBoolean(value));
} else if (field.getType() == long.class) {
  field.setAccessible(true);
  field.set(object, Long.parseLong(value));
} else if (field.getType() == int.class) {
  field.setAccessible(true);
  field.set(object, Integer.parseInt(value));
} else if (field.getType() == double.class) {
  field.setAccessible(true);
  field.set(object, Double.parseDouble(value));
} else { // String is used
  field.setAccessible(true);
  field.set(object, value);
}

}





Aucun commentaire:

Enregistrer un commentaire