Last active
December 10, 2015 22:18
-
-
Save akkerman/4501373 to your computer and use it in GitHub Desktop.
Shallow copier for objects with equivalent get/set combination
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
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