Skip to content

Instantly share code, notes, and snippets.

@akkerman
Last active December 10, 2015 22:18
Show Gist options
  • Save akkerman/4501373 to your computer and use it in GitHub Desktop.
Save akkerman/4501373 to your computer and use it in GitHub Desktop.
Shallow copier for objects with equivalent get/set combination
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CopyUtil {
public static void copy(Object src, Object dst) {
try {
for (Method getter : src.getClass().getDeclaredMethods()) {
final String getterName = getter.getName();
if (!getterName.startsWith("get") || getter.getReturnType() == void.class)
continue;
final String setterName = getterName.replaceFirst("get", "set");
final Method setter = dst.getClass().getMethod(setterName, getter.getReturnType());
setter.invoke(dst, getter.invoke(src)); // dst.setStuff(src.getStuff());
}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
// ignore
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment