how to merge properties from one Java object to another in Java using Spring [SpEL]? -
i'm using spring not familiar capabilities. looking way copy fields 1 java object instance another. i've seen how copy properties 1 java bean another? i'm looking more specific, here details:
suppose have 2 instances of class p, source & target, have getters , setters a,b,c,d , 20 others. want copy properties of of source target, properties in list of property names. not matter value of property in either source or target.
in other words, if list {"a", "b"}
want following happen:
p source; p target; list<string> properties; //source, target populated. properties {"a", "b"} //now need spring (spel?) trick equivalent of: target.seta(source.geta()); target.setb(source.getb());
using java reflection:
field[] fields = source.getclass().getdeclaredfields(); (field f: fields) { if (properties.contains(f.getname())) { f.setaccessible(true); f.set(destination, f.get(source)); } }
here 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.
using spring beanwrapper:
beanwrapper srcwrap = propertyaccessorfactory.forbeanpropertyaccess(source); beanwrapper destwrap = propertyaccessorfactory.forbeanpropertyaccess(destination); properties.foreach(p -> destwrap.setpropertyvalue(p, srcwrap.getpropertyvalue(p)));
credit spring beanwrapper example goes to: https://stackoverflow.com/a/5079864/6510058
Comments
Post a Comment