1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| public T convertFromModel(S model, T bean) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
for (Field field : model.getClass().getDeclaredFields()) {
Method getter = getGetter(model, field);
Object convertedField = null;
if (Map.class.isAssignableFrom(field.getType())) {
convertedField = convertMap((Map<Object, Object>)getter.invoke(model, null));
}
else if (Collection.class.isAssignableFrom(field.getType())) {
convertedField = convertCollection((Collection<Object>)getter.invoke(model, null));
}
else {
convertedField = convertSimpleObject(getter.invoke(model, null));
}
Method setter = getSetter(bean, field);
setter.invoke(bean, convertedField);
}
return bean;
}
private Map<?, ?> convertMap(Map<?, ?> map) throws IllegalAccessException, InstantiationException {
Map<Object, Object> convertedMap = null;
if (map != null) {
convertedMap = (Map<Object, Object>)map.getClass().newInstance();
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>)map).entrySet()) {
Object convertedKey = null;
if (entry.getKey() instanceof Map) {
convertedKey = convertMap((Map)entry.getKey());
}
else if (entry.getKey() instanceof Collection) {
convertedKey = convertCollection((Collection)entry.getKey());
}
else {
convertedKey = convertSimpleObject(entry.getKey());
}
Object convertedValue = null;
if (entry.getValue() instanceof Map) {
convertedValue = convertMap((Map)entry.getValue());
}
else if (entry.getValue() instanceof Collection) {
convertedValue = convertCollection((Collection)entry.getValue());
}
else {
convertedValue = convertSimpleObject(entry.getValue());
}
convertedMap.put(convertedKey, convertedValue);
}
}
return convertedMap;
}
private Collection<?> convertCollection(Collection<?> collection) throws IllegalAccessException, InstantiationException {
Collection<Object> convertedCollection = null;
if (collection != null) {
convertedCollection = (Collection<Object>)collection.getClass().newInstance();
for (Object object : collection) {
Object convertedObject = null;
if (object instanceof Map) {
convertedObject = convertMap((Map)object);
}
else if (object instanceof Collection) {
convertedObject = convertCollection((Collection)object);
}
else {
convertedObject = convertSimpleObject(object);
}
convertedCollection.add(convertedObject);
}
}
return convertedCollection;
}
private Object convertSimpleObject(Object object) {
// Nothing to do
return object;
} |
Partager