Java Copy Fields From One Object to Another Object with Reflection
28-11-2015Using Java Reflection, we can copy fields from one object to another object by using below class:
public class FieldCopyUtil {
public static void setFields(Object from, Object to) {
Field[] fields = from.getClass().getDeclaredFields();
for (Field field : fields) {
try {
Field fieldFrom = from.getClass().getDeclaredField(field.getName());
Object value = fieldFrom.get(from);
to.getClass().getDeclaredField(field.getName()).set(to, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
}
We can call setFields() method like this:
BelgeGuncelle belgeGuncelle = new BelgeGuncelle(); BelgeKayit belgeKayit = getBelgeKayit(belge); FieldCopyUtil.setFields(belgeKayit, belgeGuncelle);