I have this question. But it will be difficult for me to explain as I don\'t know exact terms to use. Hope someone will understand. I\'ll try to discribe to the best i can.
Dozer is fine, see Jean-Remy's answer.
Also, if the variables have getters and setters according to the JavaBeans standard, there are a number of technologies that could help you, e.g. Apache Commons / BeanUtils
Sample code (not tested):
final Map aProps = BeanUtils.describe(a);
final Map bProps = BeanUtils.describe(b);
aProps.keySet().retainAll(bProps.keySet());
for (Entry entry : aProps.entrySet()) {
BeanUtils.setProperty(b,entry.getKey(), entry.getValue());
}
Update:
If you don't have getters and setters, here's a quick hack that copies field values from one class to another as long as the fields have common names and types. I haven't tested it, but it should be OK as a starting point:
public final class Copier {
public static void copy(final Object from, final Object to) {
Map fromFields = analyze(from);
Map toFields = analyze(to);
fromFields.keySet().retainAll(toFields.keySet());
for (Entry fromFieldEntry : fromFields.entrySet()) {
final String name = fromFieldEntry.getKey();
final Field sourceField = fromFieldEntry.getValue();
final Field targetField = toFields.get(name);
if (targetField.getType().isAssignableFrom(sourceField.getType())) {
sourceField.setAccessible(true);
if (Modifier.isFinal(targetField.getModifiers())) continue;
targetField.setAccessible(true);
try {
targetField.set(to, sourceField.get(from));
} catch (IllegalAccessException e) {
throw new IllegalStateException("Can't access field!");
}
}
}
}
private static Map analyze(Object object) {
if (object == null) throw new NullPointerException();
Map map = new TreeMap();
Class> current = object.getClass();
while (current != Object.class) {
for (Field field : current.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
if (!map.containsKey(field.getName())) {
map.put(field.getName(), field);
}
}
}
current = current.getSuperclass();
}
return map;
}
}
Call Syntax:
Copier.copy(sourceObject, targetObject);