Skip to content

Instantly share code, notes, and snippets.

@gotomypc
Forked from ideiudicibus/Beanutils.java
Created October 28, 2012 05:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gotomypc/3967658 to your computer and use it in GitHub Desktop.
Save gotomypc/3967658 to your computer and use it in GitHub Desktop.
Merge two java beans useful when discovering differences
class Beanutils{
//merge two bean by discovering differences
private <M> void merge(M target, M destination) throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());
// Iterate over all the attributes
for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
// Only copy writable attributes
if (descriptor.getWriteMethod() != null) {
Object originalValue = descriptor.getReadMethod()
.invoke(target);
// Only copy values values where the destination values is null
if (originalValue == null) {
Object defaultValue = descriptor.getReadMethod().invoke(
destination);
descriptor.getWriteMethod().invoke(target, defaultValue);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment