Skip to content

Instantly share code, notes, and snippets.

@jquerius
Last active December 16, 2016 21:51
Show Gist options
  • Save jquerius/1fb5c00988c727dd6b1aa7ca034c2ec1 to your computer and use it in GitHub Desktop.
Save jquerius/1fb5c00988c727dd6b1aa7ca034c2ec1 to your computer and use it in GitHub Desktop.
Creates a domain (hibernate) object from a matching form object.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Creates a domain object from a matching form object.
* Spring parses JSON response into a form, where the
* data from the form can first be validated. Then, the
* properties of the form can be assigned to a Hibernate
* object, which a dao can use to save/update the database.
*
* This eliminates the need to manually assign many fields
* to a domain object each time this process needs to happen.
*/
public class ConvertForm {
/**
* Creates an instance of the requested object from a domain form
* @param form the web form to be converted
* @return corresponding domain object to be created
*/
public static Object createObject(Object object, Object form) {
List<Field> fields = new ArrayList<>();
fields = getAllFields(fields, object.getClass());
for (Field objectField : fields) {
try {
//get the form field and its value
Field formField = form.getClass().getDeclaredField(objectField.getName());
formField.setAccessible(true);
Object value = formField.get(form);
objectField.setAccessible(true);
objectField.set(object, value);
formField.setAccessible(false);
objectField.setAccessible(false);
} catch (NoSuchFieldException | IllegalAccessException e) {
//do nothing, it's fine if the field doesn't exist
}
}
return object;
}
/**
* Recursively checks parent object to get any inherited properties.
*/
private static List<Field> getAllFields(List<Field> fields, Class<?> type) {
fields.addAll(Arrays.asList(type.getDeclaredFields()));
if(type.getSuperclass() != null) {
fields = getAllFields(fields, type.getSuperclass());
}
return fields;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment