Skip to content

Instantly share code, notes, and snippets.

Embed
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) {
f.setAccessible(true);
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
You can’t perform that action at this time.