Skip to content

Instantly share code, notes, and snippets.

Last active December 26, 2015 19:49
What would you like to do?
Copy object field by field
public static void copyFieldByField(Object src, Object dest) {
copyFields(src, dest, src.getClass());
private static void copyFields(Object src, Object dest, Class<?> klass) {
Field[] fields = klass.getDeclaredFields();
for (Field f : fields) {
copyFieldValue(src, dest, f);
klass = klass.getSuperclass();
if (klass != null) {
copyFields(src, dest, klass);
private static void copyFieldValue(Object src, Object dest, Field f) {
try {
Object value = f.get(src);
f.set(dest, value);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment