Copy object field by field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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