I'm using Spring but not that familiar with all its capabilities. Looking for a good way to copy fields from one Java object instance to another. I've seen How to copy properties from one Java bean to another? but what i'm looking for is more specific, so here are the details:
Suppose I have two instances of some class P, source & target, which have getters and setters a,b,c,d and 20 others.
I want to copy the properties of of source into target, but only for all properties in a list of property names. It does not matter what is the value of any property in either source or target.
In other words, if the list is {"a", "b"}
then i just want the following to happen:
P source;
P target;
List<string> properties;
//source, target are populated. properties is {"a", "b"}
//Now I need some Spring (SpEL?) trick to do the equivalent of:
target.setA(source.getA());
target.setB(source.getB());
Field[] fields = source.getClass().getDeclaredFields();
for (Field f: fields) {
if (properties.contains(f.getName())) {
f.setAccessible(true);
f.set(destination, f.get(source));
}
}
Here are some tutorials on Reflection:
http://www.oracle.com/technetwork/articles/java/javareflection-1536171.html
http://tutorials.jenkov.com/java-reflection/index.html
Be careful though, Reflection has specific use cases.
BeanWrapper srcWrap = PropertyAccessorFactory.forBeanPropertyAccess(source);
BeanWrapper destWrap = PropertyAccessorFactory.forBeanPropertyAccess(destination);
properties.forEach(p -> destWrap.setPropertyValue(p, srcWrap.getPropertyValue(p)));
Credit for Spring BeanWrapper example goes to: https://stackoverflow.com/a/5079864/6510058