Dozer は問題ありません。Jean-Remy の回答を参照してください。
また、変数が JavaBeans 標準に従ってゲッターとセッターを持っている場合、Apache Commons / BeanUtilsなど、役立つテクノロジーがいくつかあります。
サンプルコード (未テスト):
final Map<String, Object> aProps = BeanUtils.describe(a);
final Map<String, Object> bProps = BeanUtils.describe(b);
aProps.keySet().retainAll(bProps.keySet());
for (Entry<String, Object> entry : aProps.entrySet()) {
BeanUtils.setProperty(b,entry.getKey(), entry.getValue());
}
アップデート:
ゲッターとセッターがない場合は、フィールドに共通の名前と型がある限り、あるクラスから別のクラスにフィールド値をコピーする簡単なハックを次に示します。私はそれをテストしていませんが、出発点としては問題ないはずです:
public final class Copier {
public static void copy(final Object from, final Object to) {
Map<String, Field> fromFields = analyze(from);
Map<String, Field> toFields = analyze(to);
fromFields.keySet().retainAll(toFields.keySet());
for (Entry<String, Field> 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<String, Field> analyze(Object object) {
if (object == null) throw new NullPointerException();
Map<String, Field> map = new TreeMap<String, Field>();
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;
}
}
呼び出し構文:
Copier.copy(sourceObject, targetObject);