how to merge properties from one Java object to another in Java using Spring [SpEL]?

拈花ヽ惹草 提交于 2019-12-11 05:54:09

问题


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());

回答1:


Using Java Reflection:

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.


Using Spring BeanWrapper:

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




回答2:


I don't think SpEL requires here, it can be solved with BeanUtils.copyProperties(Object, Object, String...). According your example, if your class has properties 'a','b','c' and you want to copy only first two, you can call it like so

BeanUtils.copyProperties(source, target, "c");

Hope it helps!



来源:https://stackoverflow.com/questions/46174746/how-to-merge-properties-from-one-java-object-to-another-in-java-using-spring-sp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!